doufu9836
2018-03-10 13:55
浏览 37
已采纳

将2D切片传递给Golang函数参数

I'm trying to scan a matrix from the stdin and simply print it using following code.

package main

import (
    "fmt"
)

func print2D(arr [][]int) {
    for i:=0; i< len(arr); i++{
        for j := 0; j< len(arr[0]); j++{
            fmt.Printf("%d ", arr[i][j])
        }
        fmt.Println()
    }
}

func main() {
    var arr [6][6]int
    for i:= 0 ; i < 6 ;i++ {
        for j := 0; j< 6; j++{
            fmt.Scanf("%d", &arr[i][j])
        }
    }
    print2D(arr[:])
}

It throws the following error

./main.go:23: cannot use arr[:] (type [][6]int) as type [][]int in argument to print2D

Is there a way to pass a 2D slice without defining sizes in the function arguments?

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douwen9540 2018-03-10 14:39
    已采纳

    Try to write the data directly to the slice and pass it later to the function. Remember array and slices are different types. Moreover, the type [3]int is also different from [4]int (size matters).

    package main
    
    import (
        "fmt"
    )
    
    func print2D(arr [][]int) {
        for i := 0; i < len(arr); i++ {
            for j := 0; j < len(arr[0]); j++ {
                fmt.Printf("%d ", arr[i][j])
            }
            fmt.Println()
        }
    }
    
    func main() {
        var arr [][]int
        for i := 0; i < 6; i++ {
            tmp := make([]int, 6)
            for j := 0; j < 6; j++ {
                fmt.Scanf("%d", &tmp[j])
            }
            arr = append(arr, tmp)
        }
        print2D(arr)
    }
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题