Go Tutorial Part 10 - Struct
Contents
1 Introduction
- like a js object
- like hash in ruby
- like dict in python
2 Define a struct
type person struct {
firstName string
lastName string
}
3 Initialize a struct
3.1 The not recommended way
alex_not_recommended := person{"Alex", "Anderson"}
fmt.Println(alex_not_recommended)
3.2 The recommended way
alex := person{firstName: "Alex" lastName:"Anderson"}
fmt.Println(alex)
3.3 Empty initialization
3.3.1 Initialization
var alex person
fmt.Println(alex)
fmt.Printf("%+v", alex)
this will initialize the struct with Zero Values
Type | Zero value |
---|---|
string | "" |
int | 0 |
bool | false |
3.3.2 Updating
alex.firstName = "Alex"
alex.lastName = "Anderson"
4 Struct Composition
4.1 Syntax 1
package main
import "fmt"
type contactInfo struct {
email string
zipCode int
}
type person struct {
firstName string
lastName string
contact contactInfo
}
func main() {
jim := person{
firstName: "Jim",
lastName: "Party",
contact: contactInfo{
email: "jim@gmail.com",
zipCode: 9400,
},
}
fmt.Printf("%+v", jim)
}
4.2 Syntax 2
Embed one struct into another
type person struct {
firstName string
lastName string
contactInfo
}
func main() {
jim := person{
firstName: "Jim",
lastName: "Party",
contactInfo: contactInfo{
email: "jim@gmail.com",
zipCode: 9400,
},
}
fmt.Printf("%+v", jim)
}
5 Struct Receiver
package main
import "fmt"
type contactInfo struct {
email string
zipCode int
}
type person struct {
firstName string
lastName string
contactInfo
}
func main() {
jim := person{
firstName: "Jim",
lastName: "Party",
contactInfo: contactInfo{
email: "jim@gmail.com",
zipCode: 9400,
},
}
jim.print()
}
//receiver
func (p person) print() {
fmt.Printf("%+v", p)
}