Answer the question
In order to leave comments, you need to log in
Why type in Go?
Good afternoon/morning/night.
I am a beginner Go developer, and I have been wondering about the meaning of type in Go for a long time. Why is she needed? What does she give? Speed? I'm especially concerned about why the type .. struct construct is needed? If all variables can be declared in var?
If possible, please provide an example on a real project.
PS I'm not very stupid, but for some reason this is what I can't understand :(
Answer the question
In order to leave comments, you need to log in
type does not create a variable, but a data type. It's like a typedef from C.
For example, you have a database, and each entry in the table can be represented as a struct.
Do type DBRecord struct {... describe all the fields, and then create a variable var myRecord DBRecord
After that, you can either read data from the database into this variable, or write new data to it and add it to the same database.
For struct, you can implement methods using functions with receiver. A set of methods implements interface - this is a kind of analogue of passing a pointer to a base class in C++. It can be transferred and used. In general, hide implementation details and focus only on the interface.
Simple example
play.golang.org/p/jtf7rlkl1m
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question