Contents

Go Tutorial Part 10 - Struct

1 Introduction

  1. like a js object
  2. like hash in ruby
  3. like dict in python

2 Define a struct

type person struct {
	firstName string
	lastName  string
}

3 Initialize a struct

alex_not_recommended := person{"Alex", "Anderson"}
fmt.Println(alex_not_recommended)
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

TypeZero value
string""
int0
boolfalse

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)
}