Kita dapat memasukkan struct ke dalam struct seperti halnya tipe data biasa. Seperti terlihat pada kode dibawah ini.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
package main import "fmt" type position struct { x, y float32 } type circle struct { p position r float32 } type rectangle struct { p position w, h float32 } func main() { c := circle{position{10, 10}, 20} fmt.Println("posisi x :", c.p.x, ", y :", c.p.y, ", r:", c.r) r := rectangle{position{5, 5}, 10, 20} fmt.Println("posisi x :", c.p.x, ", y :", c.p.y, ", w:", r.w, ", h:", r.h) } |
1 2 |
posisi x : 10 , y : 10 , r: 20 posisi x : 10 , y : 10 , w: 10 , h: 20 |
Pada contoh di atas kita dapat mengakses posisi dari circle dan rectangle dengan pengakses variable p, dan mendapatkan nilai dari x dan y nya. Struct diatas adalah struct normal tidak ada keistemewaan.