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

在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
  • 写回答

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)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
  • dongyijing2353 2019-05-18 01:04
    关注

    The problem with doing two-dimensional arrays with Go is that you have to initialise each part individually, e.g., if you have a [][]bool, you gotta allocate []([]bool) first, and then allocate the individual []bool afterwards; this is the same logic regardless of whether you're using make() or append() to perform the allocations.

    In your example, the matrix[0] doesn't exist yet after a mere var matrix [][]string, hence you're getting the index out of range error.

    For example, the code below would create another slice based on the size of an existing slice of a different type:

    func solve(board [][]rune, …) {
    
        x := len(board)
        y := len(board[0])
        visited := make([][]bool, x)
        for i := range visited {
            visited[i] = make([]bool, y)
        }
    …
    

    If you simply want to initialise the slice based on a static array you have, you can do it directly like this, without even having to use append() or make():

    package main
    
    import (
        "fmt"
    )
    
    func main() {
        matrix := [][]string{{"cat", "cat", "cat"}, {"dog", "dog"}}
        fmt.Println(matrix)
    }
    

    https://play.golang.org/p/iWgts-m7c4u

    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 Java的kafka错误unknowHostException
  • ¥20 gbase 8a没有lisense,需要获取一个lisense
  • ¥15 前端的3d饼图不知道用啥框架做的
  • ¥15 三个问答题,很简单,都是关于网络安全
  • ¥15 算法问题 斐波那契数 解答
  • ¥20 JAVAscript
  • ¥15 VS2019 SPY++ 获取句柄操作
  • ¥15 Facebook 获取广告
  • ¥15 PID算法的输出结果如何转换成pwm
  • ¥15 java文本解密算法