首页 > 其他分享 >结构体嵌套

结构体嵌套

时间:2023-02-08 21:11:17浏览次数:36  
标签:city p1 addr fmt 嵌套 address 结构 string

和json很像

package main

import "fmt"

type address struct {
  province string
  city     string
}

type person struct {
  name string
  age  int
  addr address
}

func main() {
  p1 := person{
    name: "李四",
    age:  18,
    addr: address{
      province: "安徽",
      city:     "合肥",
    },
  }
  fmt.Println(p1)
}

取出address中的省份和城市

package main

import "fmt"

type address struct {
  province string
  city     string
}

type person struct {
  name string
  age  int
  addr address //address也是一种类型,是你自己定义的类型
}

func main() {
  p1 := person{
    name: "李四",
    age:  18,
    addr: address{
      province: "安徽",
      city:     "合肥",
    },
  }
  fmt.Println(p1)
  fmt.Println(p1.addr.province)
  fmt.Println(p1.addr.city)
}
//打印的结果为:
/*
{李四 18 {安徽 合肥}}
安徽
合肥
*/

标签:city,p1,addr,fmt,嵌套,address,结构,string
From: https://www.cnblogs.com/suknna/p/17103302.html

相关文章