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)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 phython如何实现以下功能?查找同一用户名的消费金额合并—
  • ¥15 孟德尔随机化怎样画共定位分析图
  • ¥18 模拟电路问题解答有偿速度
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址