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.

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

报告相同问题?

悬赏问题

  • ¥50 pc微信3.6.0.18不能登陆 有偿解决问题
  • ¥15 求TYPCE母转母转接头24PIN线路板图
  • ¥100 国外网络搭建,有偿交流
  • ¥15 高价求中通快递查询接口
  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集