gpt4 book ai didi

go - panic : runtime error: index out of range 1

转载 作者:数据小太阳 更新时间:2023-10-29 03:47:38 28 4
gpt4 key购买 nike

我无法弄清楚这个问题,任何人都可以帮忙吗?

panic :运行时错误:索引超出范围

goroutine 1 [正在运行]:主.main() /root/go/src/k8s.io/client-go/examples/in-cluster-client-configuration/test_json.go:15 +0x42

type obj struct {
Targets [2]string `json:"targets"`
Labels map[string]string `json:"labels"`
}

func main() {
// Creating simulation
var myobj = []*obj{}
n := new(obj)
myobj[0].Targets = [2]string{"10.0.0.1", "10.0.0.2"}
myobj[0].Labels = make(map[string]string)
myobj[0].Labels["job"] = "db2"
myobj = append(myobj, n)
k := new(obj)
myobj[1].Targets = [2]string{"192.168.1.12", "192.168.1.13"}
myobj[1].Labels = make(map[string]string)
myobj[1].Labels["job"] = "mysql"
myobj = append(myobj, k)

// Converting to JSON, for transmission over web
data, err := json.Marshal(myobj)
if err != nil {
fmt.Println(err)
return
}

最佳答案

您创建了一个obj n,然后在尝试附加它之前什么都不做。所以 myobj 中还没有 obj

var myobj = []*obj{}
n := new(obj)
n.Targets = [2]string{"10.0.0.1", "10.0.0.2"}
n.Labels = make(map[string]string)
n.Labels["job"] = "db2"
myobj = append(myobj, n)
k := new(obj)
k.Targets = [2]string{"192.168.1.12", "192.168.1.13"}
k.Labels = make(map[string]string)
k.Labels["job"] = "mysql"
myobj = append(myobj, k)

关于go - panic : runtime error: index out of range 1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53038204/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com