funcnewPerson(name string) *person { p :=person(name: name} p.age =40return&p}
newPerson constructs a new person struct with the given name.
funcmain() {//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.
typerectstruct { width, height int}func (r *rect) area() int {return r.width * r.height}func (r rect) perim() int {return2*r.width +2*r.height}funcmaun() { 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
typebasestruct { num int}func (b base) describe() string {return fmt.Sprintf("base with num=%v", b.num)}//여기서 container는 base를 포함한다.typecontainerstruct {base str string}funcmain() { 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())typedescriberinterface {describe() string }var d describer= co fmt.Println("describer:", d.describe())}