紧急:运行时错误:索引超出范围1

时间:2018-10-29 03:03:32

标签: go

我不知道这个问题,有人可以帮忙吗?

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

goroutine 1 [运行中]: main.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
    }

2 个答案:

答案 0 :(得分:1)

您创建一个obj n,然后对其进行任何操作,直到尝试附加它。因此,obj中还没有myobj

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)

答案 1 :(得分:-2)

最后我想出了XD!

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

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