4.3.2 내부 필드 접근
내부 필드에는 . 연산자로 접근한다.
type Item struct { name string price float64 quantity int } func (t Item) Cost() float64 { return t.price * float64(t.quantity) } func main() { var t Item t.name = "Men's Slim-Fit Shirt" t.price = 25000 t.quantity = 3 fmt.Println(t.name) // Men's Slim-Fit Shirt fmt.Println(t.price) // 25000 fmt.Println(t.quantity) // 3 fmt.Println(t.Cost()) // 75000 }
다른 구조체를 구조체의 내부 필드로 지정하면 지정한 필드명으로 내부 구조체의 필드에 접근할 수 있다.
type dimension struct { width, height, length float64 } type Item struct { name string price float64 quantity int packageDimension dimension itemDimension dimension } func main() { shoes := Item{ "Sports Shoes", 30000, 2, dimension{30, 270, 20}, dimension{50, 300, 30}, } // 내부 필드인 dimension 구조체의 값 출력 fmt.Printf("%#v\n", shoes.itemDimension) fmt.Printf("%#v\n", shoes.packageDimension) // dimension 구조체의 내부 필드 값 출력 fmt.Println(shoes.packageDimension.width) fmt.Println(shoes.packageDimension.height) fmt.Println(shoes.packageDimension.length) }
실행 결과
main.dimension{width:50, height:300, length:30}
main.dimension{width:30, height:270, length:20}
30
270
20
Note
구조체 값을 출력할 때 필드명과 값을 함께 출력하려면 %#v를 사용하면 된다.
fmt.Printf("%#v", v)