dragon8837 2014-02-12 05:52
浏览 312
已采纳

在golang中将数组作为参数传递

Why does this not work?

package main

import "fmt"

type name struct {
    X string
}

func main() {
    var a [3]name
    a[0] = name{"Abbed"}
    a[1] = name{"Ahmad"}
    a[2] = name{"Ghassan"}

    nameReader(a)
} 

func nameReader(array []name) {
    for i := 0; i < len(array); i++ {
        fmt.Println(array[i].X)
    }
}

Error:

.\structtest.go:15: cannot use a (type [3]name) as type []name in function argument
  • 写回答

6条回答 默认 最新

  • douduikai0562 2014-02-12 06:01
    关注

    You have defined your function to accept a slice as an argument, while you're trying to pass an array in the call to that function. There are two ways you could address this:

    1. Create a slice out of the array when calling the function. Changing the call like this should be enough:

      nameReader(a[:])
      
    2. Alter the function signature to take an array instead of a slice. For instance:

      func nameReader(array [3]name) {
          ...
      }
      

      Downsides of this solution are that the function can now only accept an array of length 3, and a copy of the array will be made when calling it.

    You can find a more details on arrays and slices, and common pitfalls when using them here: http://openmymind.net/The-Minimum-You-Need-To-Know-About-Arrays-And-Slices-In-Go/

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?