duanbipu7601 2018-09-18 14:24
浏览 73
已采纳

如何传递创建二维数组的切片

I am having trouble to pass a slice of a 2d array of strings inside a func : this is my playground

Golang playground

package main

import (
    "fmt"
)

func main() {
    board := [2][3]string{
        {"O", "_", "O"},
        {"X", "O", "_"},
    }

    printBoard(board[:][:])
}

func printBoard(board [][]string){
    for _, line := range board {
        for _, cell := range line {
            fmt.Printf("%s", cell)
        }
        fmt.Println()
    }
}

It says cannot use board[:][:] (type [][3]string) as type [][]string in argument to printBoard

I did not manage to correct it printBoard(board[:][:]).

I tried by removing one/both semicolons inside the call, but did not work either. I do not want to specify any length if possible

  • 写回答

1条回答 默认 最新

  • doulu2576 2018-09-18 14:27
    关注

    In go, arrays have fixed sizes contrary to slices, so here you need to specify the size of your array as the argument, otherwise you will get this error:

    prog.go:13:12: cannot use board (type [2][3]string) as type [][]string in argument to printBoard

    Here it is fixed:

    package main
    
    import (
        "fmt"
    )
    
    func main() {
        board := [2][3]string{
            {"O", "_", "O"},
            {"X", "O", "_"},
        }
    
        printBoard(board)
    }
    
    func printBoard(board [2][3]string){
        for _, line := range board {
            for _, cell := range line {
                fmt.Printf("%s", cell)
            }
            fmt.Println()
        }
    }
    

    Outputs

    O_O
    XO_
    

    I'm not sure why you decided to use arrays but in go, whenever possible you should prefer using slices instead of arrays, as they're more flexible, cleaner and less bug-prone.

    Here is the implementation with slices instead:

    package main
    
    import (
        "fmt"
    )
    
    func main() {
        board := [][]string{
            {"O", "_", "O"},
            {"X", "O", "_"},
        }
    
        printBoard(board)
    }
    
    func printBoard(board [][]string){
        for _, line := range board {
            for _, cell := range line {
                fmt.Printf("%s", cell)
            }
            fmt.Println()
        }
    }
    

    Note that you don't need to change your logic, and you don't need to specify sizes anywhere anymore.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集