Structs in Go

 This is a study note from YouTube tutorial: https://www.youtube.com/watch?v=YS4e4q9oBaU&t=7285s

You can define a struct and initialise it using following example:

type Doctor struct {
Number int
ActorName string
Companions []string
}

func main() {
aDoctor := Doctor{
Number: 3,
ActorName: "Jon Pertwee",
Companions: []string{
"Liz Shaw",
"Jo Grant",
"Sarah Jane Smith",
},
}
fmt.Println(aDoctor)
fmt.Println(aDoctor.ActorName)
}

You can dot operator (".") to access the fields in a struct.

Anonymous struct 

You can create an anonymous struct for informal uses in Go.

func main() {
aDoctor := struct{ name string }{name: "John Pertwee"}
fmt.Println(aDoctor)
}


Struct is a value type

Unlike map is a reference type, struct is a value type. This means if you assign one struct to another, the struct will be made a copy and assign to the other. Any modification in one struct won't impact the others.

func main() {
aDoctor := struct{ name string }{name: "John Pertwee"}
anotherDoctor := aDoctor
anotherDoctor.name = "Tom Baker"
fmt.Println(aDoctor)
fmt.Println(anotherDoctor)
}

The result is:

{John Pertwee} {Tom Baker}

Same like array, if you want two struct refer to the same location, you can use pointer to do so.

func main() {
aDoctor := struct{ name string }{name: "John Pertwee"}
anotherDoctor := &aDoctor // Pass the address of aDoctor to anotherDoctor
anotherDoctor.name = "Tom Baker"
fmt.Println(aDoctor)
fmt.Println(anotherDoctor)
}

The result is:

{Tom Baker} &{Tom Baker}

Embedded type of struct

You can embed a struct in another struct by simply declaring the embedding struct in the other. For example:

type Animal struct {
Name string
Origin string
}

type Bird struct {
Animal
SpeedKPH float32
CanFly bool
}

func main() {
b := Bird{}
b.Name = "Emu"
b.Origin = "Australia"
b.SpeedKPH = 48
b.CanFly = false

fmt.Println(b)
}

The result is:

{{Emu Australia} 48 false}

You can also initialise the struct in a structured way, however you can still refer the fields in the embedded struct directly.

func main() {
b := Bird{
Animal: Animal{Name: "Emu", Origin: "Australia"},
SpeedKPH: 48,
CanFly: false,
}
fmt.Println(b.Name)
}

The result is:

Emu




Reference: https://www.youtube.com/watch?v=YS4e4q9oBaU&t=7285s

Comments

Popular posts from this blog

Basic understanding of TLS-PSK protocol

Differences between ASIC, ASSP and ASIP

Orthogonal instruction set