php小編蘋果在這里為大家介紹一下Go語言中的struct變量。在Go語言中,struct是一種自定義的數據類型,用于封裝一組相關的數據字段。它類似于其他編程語言中的類或結構體,可以包含各種類型的字段,如整數、字符串、布爾值等。通過定義struct變量,我們可以方便地組織和管理數據,使代碼更加清晰和易于維護。無論是在Web開發、系統編程還是其他領域,struct都是Go語言中非常重要的一個概念,值得我們深入學習和理解。
問題內容
我怎樣才能得到這個輸出?
type datas struct {
age int
height int
weight int
}
func main(){
var age := 5
var height := 10
var weight := 15
namelist := []string{"b", "c", "d"}
for count, a := range namelist {
a := datas{age+count,height+count,weight+count}
//Expected Output: b{6,11,16} , c{7,12,17}, d{8,13,18}
}
}
登錄后復制
我找不到有關此案例的任何信息,我猜不包括此功能。對于這種情況有什么解決辦法嗎?
解決方法
相反,您可以使用鍵名稱將數據放在地圖上
type datas struct {
age int
height int
weight int
}
func main(){
structMap := make(map[string]interface{})
age := 5
height := 10
weight := 15
namelist := []string{"b", "c", "d"}
for count, val := range namelist {
count = count + 1 // this is due to your expected output
out := datas{age+count,height+count,weight+count}
structMap[val] = out
}
fmt.Println(structMap)
// output: map[b:{6 11 16} c:{7 12 17} d:{8 13 18}]
}
登錄后復制






