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

如何在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)
}

图片转代码服务由CSDN问答提供 功能建议

因此,我希望能够将矩阵作为函数传递给Golang中的参数。 每次的大小可能都不同-例如4x4矩阵,3x2矩阵等。如果我尝试对源代码运行以下测试代码,则会收到错误消息,例如:

如何将二维数组传递给函数? 我是Go语言的新手,来自动态语言背景(Python,Ruby)。

 不能使用mat [:] [:](类型[] [3] int  )设置为zeroReplaceMatrix 
   
 
 

源代码

 <  code> func ReplaceMatrix(mat [] [] int,rows,cols,a,b int){
 
} 
   
 
 

测试代码< / strong>

  func TestReplaceMatrix(t * testing.T){
 var mat [3] [3] int 
 //某些代码
得到了:= 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:

    已采纳该答案
    打赏 评论

相关推荐 更多相似问题