- like a js object
- like hash in ruby
- like dict in python
type person struct {
firstName string
lastName string
}
|
alex_not_recommended := person{"Alex", "Anderson"}
fmt.Println(alex_not_recommended)
|
alex := person{firstName: "Alex" lastName:"Anderson"}
fmt.Println(alex)
|
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 |
alex.firstName = "Alex"
alex.lastName = "Anderson"
|
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)
}
|
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)
}
|
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)
}
|