package main
import (
"fmt"
)
type person struct {
Id int
Name string
Sex byte
}
func changeStructValue(p *person) {
p.Id = 2
}
type Point struct {
X, Y int
}
type Circle struct {
Point
Radius int
}
type Wheel struct {
Circle
Spokes int
}
func main() {
p1 := person{
Id: 1,
Name: "w",
Sex: 'm',
}
p1.Name = "hy"
fmt.Println(p1) // {1 hy 109}
// 结构体做函数参数
changeStructValue(&p1)
fmt.Println(p1) // {2 hy 109}
// 结构体嵌入和匿名成员
var p2 Wheel
p2.X = 10
p2.Y = 20
p2.Radius = 25
p2.Spokes = 30
fmt.Println(p2) // {{{10 20} 25} 30}
p3 := Wheel{
Circle: Circle{
Point: Point{
X: 100,
Y: 200,
},
Radius: 250,
},
Spokes: 300,
}
fmt.Println(p3) // {{{100 200} 250} 300}
// 结构体slice
p4 := []person{
{
Id: 2,
Name: "ww",
Sex: 'f',
},
{
Id: 3,
Name: "wy",
Sex: 'm',
},
}
fmt.Println(p4)
}
结构体字段可以直接访问,或者通过指针访问
type Vertex struct {
X int
Y int
}
func main() {
v := Vertex{1, 2}
p := &v
v.X = 10
p.Y = 20
fmt.Println(v) // {10 20}
}