在 array 當中儲存的相同類型的元素,那如果需要儲存不同的類型的數據集合,這時候我們要討論到 Struct
在 Strcut 當中會將元素進行命名及定義類型,這裡我們稱為 fields
定義的名稱首字大小區分,Private 或者 Public
package main
import (
"fmt"
)
type Member struct {
Name string
Age int
Gender string
}
func main() {
//宣告 變數 p 為 Member 類型
var p Member
//未賦值 則 feild value 為預設值
fmt.Println(p)
p.Name = "Camille"
p.Age = 18
p.Gender = "女生"
fmt.Println(p)
//宣告及賦予值
m := Member{
Name: "derek",
Age: 20,
Gender: "男生",
}
fmt.Println(m)
// 不寫 feild 依序賦予值
p2 := Member{"tom", 30, "男生"}
fmt.Println(p2)
}
package main
import "fmt"
type Member struct {
Name string
Age int
}
func main() {
p := Member{
Name: "john",
Age: 11,
}
p2 := p
p2.Name = "tom"
//互相不引響
fmt.Printf("%+v\n", p)
fmt.Printf("%+v\n", p2)
//pointer Member 類型
pp := &p
//pointer 賦值
(*pp).Name = "Jack"
fmt.Printf("%+v\n", p)
fmt.Printf("%+v\n", pp)
//也可以省略"*" 已經底層優化處理
pp.Name = "Noah"
pp.Age = 19
fmt.Printf("%+v\n", p)
fmt.Printf("%+v\n", pp)
//使用 new 來產生 pointer Member 類型
pp2 := new(Member)
fmt.Printf("%T\n", pp2)
pp2.Name= "Thomas"
}
常用於一次性
package main
import "fmt"
func main() {
p := struct {
Name string
Age int
}{
Name: "john",
Age: 18,
}
fmt.Println(p)
}
可以看出 Struct feild pointer 為連續分配
package main
import (
"fmt"
)
type Point struct {
x int
y int
}
type Rect struct {
leftUp, rightDown Point
}
func main() {
p := Point{
x: 1,
y: 2,
}
fmt.Printf("point 地址: %p p.x point: %p p.y point: %p\n", &p, &p.x, &p.y)
r1 := Rect{Point{1, 2}, Point{3, 4}}
fmt.Printf("r1 地址: %p r1.leftUp point: %p r1.leftUp.x point: %p r1.leftUp.y point: %p\n", &r1, &r1.leftUp, &r1.leftUp.x, &r1.leftUp.y)
fmt.Printf("r1 地址: %p r1.rightDown point: %p r1.rightDown .x point: %p r1.leftUp.y point: %p\n", &r1, &r1.leftUp, &r1.leftUp.x, &r1.leftUp.y)
}