在golang中将数组作为参数传递 [英] Passing an array as an argument in golang

查看:118
本文介绍了在golang中将数组作为参数传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这不起作用?

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

错误:

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

推荐答案

在尝试将调用中的数组传递给该函数时,您已将函数定义为接受切片作为参数.有两种解决方法:

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. 在调用函数时从数组中创建一个切片.像这样更改通话就足够了:

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

nameReader(a[:])

  • 更改函数签名以采用数组而不是切片.例如:

  • Alter the function signature to take an array instead of a slice. For instance:

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

    该解决方案的缺点是该函数现在只能接受长度为3的数组,并且在调用该数组时将创建该数组的副本.

    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/

    这篇关于在golang中将数组作为参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆