douguaidian8021
2018-08-14 19:55
采纳率: 100%
浏览 1.2k
已采纳

在golang中创建二维字符串数组

I need to create a 2 dimensional string array as shown below -

matrix = [['cat,'cat','cat'],['dog','dog']]

Code:-

package main

import (
    "fmt"
)

func main() {
    { // using append

    var matrix [][]string
    matrix[0] = append(matrix[0],'cat')
        fmt.Println(matrix)
    }
}

Error:-

panic: runtime error: index out of range

goroutine 1 [running]:
main.main()
    /tmp/sandbox863026592/main.go:11 +0x20

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

我需要创建一个二维字符串数组,如下所示-

   matrix = [['cat,'cat','cat'],['dog','dog']] 
   
 
 

代码:-< / p>

 包main 
 
import(
“ fmt” 
)
 
func main(){
 {//使用append 
 
 var matrix [  ] [] string 
 matrix [0] = append(matrix [0],'cat')
 fmt.Println(matrix)
} 
} 
   
 
  

错误:-

 紧急:运行时错误:索引超出范围
 
goroutine 1 [正在运行]:
main.main()
 / tmp / sandbox863026592  /main.go:11 + 0x20 
   
 
  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • duanjue2560 2018-08-14 20:05
    已采纳

    You have a slice of slices, and the outer slice is nil until it's initialized:

    matrix := make([][]string, 1)
    matrix[0] = append(matrix[0],'cat')
    fmt.Println(matrix)
    

    Or:

    var matrix [][]string
    matrix = append(matrix, []string{"cat"})
    fmt.Println(matrix)
    

    Or:

    var matrix [][]string
    var row []string
    row = append(row, "cat")
    matrix = append(matrix, row)
    
    评论
    解决 无用
    打赏 举报
查看更多回答(1条)

相关推荐 更多相似问题