解决函数的返回片时出错 [英] Error addressing the returned slice of a function

查看:65
本文介绍了解决函数的返回片时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下一个代码中,第一个 Println 在构建时失败,错误为 slice of unaddressable value .其余各行都很好.

In the next code the first Println fails on build with error slice of unaddressable value. The rest of the lines are just fine.

package main

import "fmt"

func getSlice() [0]int {
   return [...]int{}
}

func getString() string {
   return "hola"
}

func main() {
    fmt.Println(getSlice()[:]) // Error: slice of unaddressable value

    var a = getSlice()
    fmt.Println(a[:])

    fmt.Println(getString()[:])

    var b = getString()
    fmt.Println(b[:])
}

尝试此代码

如果第一个 Println 被注释,它将起作用.尝试一下

If the first Println is commented it works. Try it out

那是为什么?我在这里想念的是什么?

Why is that? What I'm missing here?

推荐答案

您缺少的是,在切片 array 时,操作数必须是可寻址的( [0] int 是一个数组,而不是切片).并且函数调用的返回值不可寻址.有关详细信息,请参见如何在Go中存储对操作结果的引用?;和不能接受"的地址和无法在其上调用指针方法" .

What you're missing is that when slicing an array, the operand must be addressable ([0]int is an array, not a slice). And return values of function calls are not addressable. For details see How can I store reference to the result of an operation in Go?; and "cannot take the address of" and "cannot call pointer method on".

规范:切片表达式:

如果切片的操作数是一个数组,则它必须是可寻址的,并且其结果必须是 addressable .切片操作是与数组具有相同元素类型的切片.

If the sliced operand is an array, it must be addressable and the result of the slice operation is a slice with the same element type as the array.

在此表达式中:

getSlice()[:]

getSlice()返回一个 array ,由于它是函数调用的结果,因此无法寻址.因此,您无法对其进行切片.

getSlice() returns an array, and since it's the result of a function call, it's not addressable. Therefore you cannot slice it.

在此表达式中:

getString()[:]

getString()返回一个 string 值,因此即使该值不可寻址也可以对其进行切片.之所以允许这样做,是因为slice表达式的结果将是另一个 string ,并且Go中的 string 值是不可变的.

getString() returns a string value, so it can be sliced even if the value is not addressable. This is allowed, because the result of the slice expression will be another string, and string values in Go are immutable.

此外,变量是可寻址,因此它将始终有效:

Also, variables are addressable, so this will always work:

var a = getSlice()
fmt.Println(a[:])

这篇关于解决函数的返回片时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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