Structs

  • Go's structs are typed collections of fields.

type person struct {
    name string
    age  int
} 
  • This person struct type has name and age fields.

func newPerson(name string) *person {

    p := person(name: name}
    p.age = 40
    return &p
}
  • newPerson constructs a new person struct with the given name.

func main() {

	//creates a new struce
	fmt.Println(person{"Bob", 20})
	//you can name the fields when initializing
	fmt.Println(person{name: "Alice", age: 30})
	//Omitted fields will be zero-valued.
	fmt.Println(person{name: "Fred"})
	//An & prefix tields a pointer to the struct - out : &{Ann, 40}
	fmt.Println(&person{"Ann", 40})
	
	fmt.Println(newPerson("Jon"))

	s := person{name: "Sean", age: 50}
	fmt.Println(s.name)

	sp := &s
	fmt.Println(sp.age)
}

Methods

  • Go supports methods defined on struct types.

type rect struct {
    width, height int
}

func (r *rect) area() int {
    return r.width * r.height
}

func (r rect) perim() int {
    return 2*r.width + 2*r.height
}

func maun() {
    r := rect{width: 10, height: 5}
    
    fmt.Println("area: ", r.area())
    fmt.Println("perim:", r.perim())
    
    rp := &r
    fmt.Println("area: ", rp.area())
    fmt.Println("perim:", rp.perim())
}
  • Go automatically handles conversion between values and pointers for method calls.

Struct Embedding

type base struct {
	num int
}

func (b base) describe() string {
	return fmt.Sprintf("base with num=%v", b.num)
}
//여기서 container는 base를 포함한다.
type container struct {
	base
	str string
}

func main() {

	co := container{
		base: base{
			num: 1,
		},
		str: "some name",
	}
	//이렇게 바로 num에 접근하는것도 가능하
	fmt.Printf("co={num: %v, str: %v}\n", co.num, co.str)
	//base를 통해 num에 접근할 수 도 있다.
	fmt.Println("also num:", co.base.num)

	fmt.Println("descrebe:", co.describe())

	type describer interface {
		describe() string
	}

	var d describer = co
	fmt.Println("describer:", d.describe())
}

Last updated