从函数返回语句中创建Go数组切片

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

Go array slice from function return statement

问题

我有以下函数:

func (c *Class)A()[4]byte
func B(x []byte)

我想调用

B(c.A()[:])

但是我得到了这个错误:

无法获取 c.(*Class).A() 的地址

在Go语言中,如何正确地获取函数返回的数组的切片?

英文:

I have the following functions:

func (c *Class)A()[4]byte
func B(x []byte)

I want to call

B(c.A()[:])

but I get this error:

cannot take the address of c.(*Class).A()

How do I properly get a slice of an array returned by a function in Go?

答案1

得分: 10

c.A()方法的返回值[4]byte是不可寻址的。

寻址操作符

对于类型为T的操作数x,寻址操作符&x会生成一个类型为*T的指针,指向x。操作数必须是可寻址的,即变量、指针间接引用或切片索引操作;或者是可寻址结构体操作数的字段选择器;或者是可寻址数组的数组索引操作。作为对可寻址要求的例外,x也可以是一个复合字面量。

切片

如果被切片的操作数是字符串或切片,切片操作的结果是相同类型的字符串或切片。如果被切片的操作数是数组,它必须是可寻址的,切片操作的结果是具有与数组相同元素类型的切片。

使c.A()方法的返回值[4]byte可寻址,以便进行切片操作[:]。例如,将该值赋给一个变量;变量是可寻址的。

例如,

package main

import "fmt"

type Class struct{}

func (c *Class) A() [4]byte { return [4]byte{0, 1, 2, 3} }

func B(x []byte) { fmt.Println("x", x) }

func main() {
    var c Class
    // B(c.A()[:]) // 无法获取c.A()的地址
    xa := c.A()
    B(xa[:])
}

输出:

x [0 1 2 3]
英文:

The value of c.A(), the return value from a method, is not addressable.

> Address operators
>
> For an operand x of type T, the address operation &x generates a
> pointer of type *T to x. The operand must be addressable, that is,
> either a variable, pointer indirection, or slice indexing operation;
> or a field selector of an addressable struct operand; or an array
> indexing operation of an addressable array. As an exception to the
> addressability requirement, x may also be a composite literal.
>
> Slices
>
> If the sliced operand is a string or slice, the result of the slice
> operation is a string or slice of the same type. 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.

Make the value of c.A(), an array, addressable for the slice operation [:]. For example, assign the value to a variable; a variable is addressable.

For example,

package main

import "fmt"

type Class struct{}

func (c *Class) A() [4]byte { return [4]byte{0, 1, 2, 3} }

func B(x []byte) { fmt.Println("x", x) }

func main() {
	var c Class
	// B(c.A()[:]) // cannot take the address of c.A()
	xa := c.A()
	B(xa[:])
}

Output:

x [0 1 2 3]

答案2

得分: 2

你尝试过先将数组放入一个本地变量中吗?

ary := c.A()
B(ary[:])
英文:

Have you tried sticking the array in a local variable first?

ary := c.A()
B(ary[:])

huangapple
  • 本文由 发表于 2011年11月30日 06:26:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/8318634.html
匿名

发表评论

匿名网友

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

确定