Learning Go — from zero to hero

A struct can be defined using the following syntax:With a person type struct defined, now let’s create a person:We can easily access these data with a dot(.)You can also access attributes of a struct directly with its pointer:MethodsMethods are a special type of function with a receiver..A receiver can be both a value or a pointer..Let’s create a method called describe which has a receiver type person we created in the above example:As we can see in the above example, the method now can be called using a dot operator as pp.describe..Note that the receiver is a pointer..With the pointer we are passing a reference to the value, so if we make any changes in the method it will be reflected in the receiver pp..It also does not create a new copy of the object, which saves memory.Note that in the above example the value of age is changed, whereas the value of name is not changed because the method setName is of the receiver type whereas setAge is of type pointer.InterfacesGo interfaces are a collection of methods..Interfaces help group together the properties of a type..Let’s take the example of an interface animal:Here animal is an interface type..Now let’s create 2 different type of animals which implement the animal interface type:In the main function, we create a variable a of type animal..We assign a snake and a cat type to the animal and use Println to print a.description..Since we have implemented the method describe in both of the types (cat and snake) in a different way we get the description of the animal printed.PackagesWe write all code in Go in a package..The main package is the entry point for the program execution.. More details

Leave a Reply