Basic Structs

We combine basic types to a collection which is called a struct:

Lets model a superhero.

It has a name, and strength index for the first pitch:

type Supe struct{
    name string
    strength int
}

If the name Supe starts with a capital letter, it can be used from other packages.

After defining the struct, we may use it to initialize variables:

package main
 
import (
    "fmt"
)
 
type Supe struct{
    name string
    strength int
}
 
func main() {
    var  shazam Supe
    fmt.Println(shazam) 
}

We get the empty name and and “empty” int, initialized to “0”. So the output is:

{ 0}

Now the data can be assigned:

shazam.name = "shazam"
shazam.strength  = 300
fmt.Println(shazam) 

And we get the output

{shazam 300}

Copy structs

Just as simple types we can copy the structs.

With

son := shazam
fmt.Println(son)

We get {shazam 300} as output again. And the son is independent from shazam.

When we set the son strength to 200, shazam will remain at 300:

son.strength = 200
fmt.Println(son)
fmt.Println(shazam) 

Output:

{shazam 200}
{shazam 300}

Using “new”

And if you really want to, you can have a new keyword:

daughter := new(Supe)
daughter.strength = 400
fmt.Println(daughter)

But new returns a pointer to the struct, so this will output:

&{ 400}

If you want to have just the struct, you use the * dereference again:

fmt.Println(*daughter)

Source

See the full source on github.

Sources