golang入门到放弃:4.结构体

定义

type 结构体名称 struct {

    属性1名称   属性1类型

    属性2名称   属性2类型
   ...
}
  • eg:
//定义一个游戏玩家结构体
type Player struct {
    id int
    nickName string
    job string
    level int
}

func main(){
    p:=Player{10001,"靓仔","ADC",1}
    fmt.Printf("%T",p) //main.Player
    fmt.Println(p)//{10001 靓仔 ADC 1}

    p.level++
    fmt.Println(p)//{10001 靓仔 ADC 2}

    p2:=Player{10002,"小马仔","TANK",10}

    var maxLvP Player
    if p.level>p2.level {
        maxLvP=p
    }else{
        maxLvP=p2
    }

    fmt.Printf("等级高的玩家名称:%s",maxLvP.nickName)//等级高的玩家名称:小马仔
}

结构体数组

结构体数组

  • 定义 结构体数组名 [元素个数]结构体类型

  • eg

    //var arr [5]Player
    playerList:=[2]Player{}
      playerList[0].nickName="小马仔1号"
      playerList[0].job="ADC"
      playerList[0].level=100
      playerList[0].id=100
    
      playerList[1].nickName="小马仔2号"
      playerList[1].job="ADC"
      playerList[1].level=200
      playerList[1].id=101
    
    
      fmt.Println(playerList)//[{100 小马仔1号 ADC 100} {101 小马仔2号 ADC 200}]
    

结构体切片

  • 定义 [元素个数]数组 结构体类型

  • eg

    playerList:=[]Player{}
    playerList:=[]Player{}
    //追加切片元素
    playerList = append(playerList, Player{1,"小马仔3号","TANK",1})
    fmt.Println(playerList) //[{1 小马仔3号 TANK 1}]
    

结构体map

  • 定义 map[类型] 结构体

  • eg

    //定义map
      playerMap:=make(map[string]Player)
      playerMap["ADC"] = Player{110,"靓仔1号","ADC",99}
      playerMap["Tank"] = Player{110,"靓仔2号","TANK",99}
      fmt.Println(playerMap)//map[ADC:{110 靓仔1号 ADC 99} Tank:{110 靓仔2号 TANK 99}]
    

结构体map 切片

  • 定义 map[类型][]结构体

  • eg

    playerMap:=make(map[string][]Player)
    playerMap["ADC"] = append( playerMap["ADC"],Player{110,"靓仔1号","ADC",99})
    playerMap["ADC"] = append( playerMap["ADC"],Player{111,"靓仔111号","ADCC",1})
    playerMap["Tank"] = append(playerMap["Tank"],Player{112,"靓仔2号","TANK",99})
    playerMap["Tank"] = append(playerMap["Tank"],Player{113,"靓仔112号","TANK",99})
    fmt.Println(playerMap)//map[ADC:[{110 靓仔1号 ADC 99} {111 靓仔111号 ADCC 1}] Tank:[{112 靓仔2号 TANK 99} {113 靓仔112号 TANK 99}]]
    

你可能感兴趣的:(golang入门到放弃:4.结构体)