英文:
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[:])
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论