duanpai9945 2015-07-14 14:32
浏览 1220
已采纳

如何在Go中将二维数组作为函数参数传递?

So I want to be able to pass a matrix as a function in an argument in Golang. It could be a different size each time - e.g., a 4x4 matrix, 3x2 matrix, etc. If I try running the test code below against the source code I get an error message like:

How do I pass a 2 dimensional array into a function? I'm new to Go and come from a dynamic language background (Python, Ruby).

cannot use mat[:][:] (type [][3]int) as type [][]int in argument to zeroReplaceMatrix

source code

func ReplaceMatrix(mat [][]int, rows, cols, a, b int) {

}

test code

func TestReplaceMatrix(t *testing.T) {
    var mat [3][3]int
    //some code
    got := ReplaceMatrix(mat[:][:], 3, 3, 0, 1)
}
  • 写回答

1条回答 默认 最新

  • dqqvravff05370501 2015-07-14 14:52
    关注

    The easiest way to use slices. Unlike arrays they are passed by reference,not by value. For example:

    package main
    
    import "fmt"
    
    type Matrix [][]float64
    func main() {
        oneMatrix := Matrix{{1, 2}, {2, 3}}
        twoMatrix := Matrix{{1, 2,3}, {2, 3,4}, {5, 6,7}}
        print (oneMatrix)
        print (twoMatrix)
    
    }
    func print(X Matrix) {
        for _, i := range X {
            for _, j := range i {
                fmt.Printf("%f ", j)
            }
            fmt.Println()
        }
    }
    

    link:

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

报告相同问题?

悬赏问题

  • ¥30 Matlab打开默认名称带有/的光谱数据
  • ¥50 easyExcel模板 动态单元格合并列
  • ¥15 res.rows如何取值使用
  • ¥15 在odoo17开发环境中,怎么实现库存管理系统,或独立模块设计与AGV小车对接?开发方面应如何设计和开发?请详细解释MES或WMS在与AGV小车对接时需完成的设计和开发
  • ¥15 CSP算法实现EEG特征提取,哪一步错了?
  • ¥15 游戏盾如何溯源服务器真实ip?需要30个字。后面的字是凑数的
  • ¥15 vue3前端取消收藏的不会引用collectId
  • ¥15 delphi7 HMAC_SHA256方式加密
  • ¥15 关于#qt#的问题:我想实现qcustomplot完成坐标轴
  • ¥15 下列c语言代码为何输出了多余的空格