Go Tutorial Part 10 - Struct

Contents
  1. like a js object
  2. like hash in ruby
  3. 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

TypeZero value
string""
int0
boolfalse
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)
}