douqian1835
2018-10-29 03:03
浏览 136
已采纳

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

i can not figure out this problem ,anyone can help?

panic: runtime error: index out of range

goroutine 1 [running]: 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
    }

图片转代码服务由CSDN问答提供 功能建议

我无法解决此问题,有人可以帮忙吗?

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

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

  type obj struct {
目标[2  ] string`json:“ targets”`
标签map [string] string`json:“ labels”`
} 
 
func main(){
 //创建模拟
 var myobj = [] * obj  {} 
n:= new(obj)
 myobj [0]。目标= [2]字符串{“ 10.0.0.1”,“ 10.0.0.2”} 
 myobj [0]。标签= 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] .Label = make(map [string] string)
 myobj [1] .Labels [“ job”] =“ mysql” 
  myobj = append(myobj,k)
 
 //转换为JSON,以通过Web传输n数据,err:= json.Marshal(myobj)
如果err!= nil {
 fmt.Println(err  )
返回
} 
   
 
  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dpxbc88022 2018-10-29 03:13
    已采纳

    finally i figure this out 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)
    
    评论
    解决 无用
    打赏 举报
查看更多回答(1条)

相关推荐 更多相似问题