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

huangapple go评论121阅读模式
英文:

How to pass a 2 dimensional array as a function argument in Go?

问题

我想要能够在 Golang 中将矩阵作为函数参数传递。每次可能是不同的大小,例如 4x4 矩阵、3x2 矩阵等。如果我尝试运行下面的测试代码与源代码进行对比,会收到如下错误信息:

如何将二维数组传递给函数?我是 Go 的新手,之前使用的是动态语言(Python、Ruby)。

源代码

  1. func ReplaceMatrix(mat [][]int, rows, cols, a, b int) {
  2. }

测试代码

  1. func TestReplaceMatrix(t *testing.T) {
  2. var mat [3][3]int
  3. //一些代码
  4. got := ReplaceMatrix(mat[:][:], 3, 3, 0, 1)
  5. }
英文:

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).

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

source code

  1. func ReplaceMatrix(mat [][]int, rows, cols, a, b int) {
  2. }

test code

  1. func TestReplaceMatrix(t *testing.T) {
  2. var mat [3][3]int
  3. //some code
  4. got := ReplaceMatrix(mat[:][:], 3, 3, 0, 1)
  5. }

答案1

得分: 10

使用切片的最简单方法。与数组不同,它们是通过引用而不是值传递的。例如:

  1. package main
  2. import "fmt"
  3. type Matrix [][]float64
  4. func main() {
  5. oneMatrix := Matrix{{1, 2}, {2, 3}}
  6. twoMatrix := Matrix{{1, 2, 3}, {2, 3, 4}, {5, 6, 7}}
  7. print(oneMatrix)
  8. print(twoMatrix)
  9. }
  10. func print(X Matrix) {
  11. for _, i := range X {
  12. for _, j := range i {
  13. fmt.Printf("%f ", j)
  14. }
  15. fmt.Println()
  16. }
  17. }

链接:

英文:

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

  1. package main
  2. import "fmt"
  3. type Matrix [][]float64
  4. func main() {
  5. oneMatrix := Matrix{{1, 2}, {2, 3}}
  6. twoMatrix := Matrix{{1, 2,3}, {2, 3,4}, {5, 6,7}}
  7. print (oneMatrix)
  8. print (twoMatrix)
  9. }
  10. func print(X Matrix) {
  11. for _, i := range X {
  12. for _, j := range i {
  13. fmt.Printf("%f ", j)
  14. }
  15. fmt.Println()
  16. }
  17. }

link:

huangapple
  • 本文由 发表于 2015年7月14日 22:32:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/31409627.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定