Go 结构体

1. type关键字

  • 定义类型别名
type myInt = int
var a myInt = 1
var b int = 2
fmt.Println(a + b)
  • 类型定义

  • 定义接口

  • 定义结构体

  • 类型判断

2. 结构体

  • 定义结构体
type person struct {
   name    string
   age     int
   address string
   height  float32
}
  • 赋值
func main() {
   // 赋值方式1
   p1 := person{"tom", 18, "go", 1.80}
   p1.name = "boby" 
   // 复制方式2
   p2 := person{name: "tom", age: 18, address: "go", height: 1.80}
}
  • 取值
fmt.Println(p1.name)
fmt.Println(p2.name)

2.匿名结构体

func main() {
	address := struct {
		province string
		city     string
		address  string
	}{
		"省份",
		"城市",
		"地址",
	}
	fmt.Println(address.city)
}

3.结构体嵌套

  • 定义
type myAddress struct {
   province string
   city     string
   address  string
}
type person struct {
   name    string
   age     int
   address myAddress
   height  float32
}
  • 赋值
func main() {
   p1 := person{
      name: "tom",
      age:  18,
      address: myAddress{
         province: "省份",
         city:     "城市",
         address:  "地址",
      },
      height: 1.80,
   }
   p1.address.city = "城市1"
   fmt.Println(p1)
}
  • 取值
fmt.Println(p1.address.city)

4. 结构体方法

// 结构体
type myAddress struct {
   province string
   city     string
   address  string
}

// 附在结构体上的方法,(方法名之前的括号)
func (ma myAddress) myPrint() {
   fmt.Println(ma.province, ma.city, ma.address)
}

func main() {
   my := myAddress{"省份", "城市", "地址"}
   my.myPrint()
}
posted @ 2023-03-13 15:48  ForLivetoLearn  阅读(12)  评论(0编辑  收藏  举报