寻址返回的函数切片时出错

Error addressing the returned slice of a function

在接下来的代码中,第一个 Println 构建失败并出现错误 slice of unaddressable value。其余的台词就好了。

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[:])
}

Try this code

如果第一个 Println 被评论,它就有效。 Try it out

这是为什么?我在这里缺少什么?

您缺少的是,在对 数组 进行切片时,操作数必须是可寻址的([0]int 是数组,而不是切片)。 return 函数调用的值不可寻址。有关详细信息,请参阅 ; and

Spec: Slice expressions:

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() return 是一个 数组 ,因为它是函数调用的结果,所以它不可寻址。所以不能切片。

在此表达式中:

getString()[:]

getString() return 是一个 string 值,因此即使该值不可寻址也可以对其进行切片。这是允许的,因为切片表达式的结果将是另一个 string,而 string 值在 Go 中是不可变的。

此外,变量是 addressable,所以这将始终有效:

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

getSlice() 不是 return 切片它是 return 数组,这是不可寻址的。您可以 return 指向数组的指针:

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

或保留getSlice()原样并将结果放在临时变量中:

t := getSlice()
fmt.Println(t[:])