Go to array of array from return function statement

I have the following functions:

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

I want to call

 B(cA()[:]) 

but I get this error:

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

How to get the piece of array returned by a function in Go correctly?

+6
source share
2 answers

The value cA() , the return value of the method is not addressed.

Address Operators

For operand x of type T, the address operation & x creates a pointer of type * T to x. The operand must be addressable, i.e. either a variable, a pointer pointer, or a fragment indexing operation; or field selector of an address structural operand; or array indexing operation of the address array. As an exception to the targeting requirement, x can also be a composite literal.

fragments

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

Make the value cA() , the array addressed to the slice [:] operation. For example, assign a value to a variable; the variable is addressed.

For instance,

 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(cA()[:]) // cannot take the address of cA() xa := cA() B(xa[:]) } 

Conclusion:

 x [0 1 2 3] 
+8
source

Did you try to insert the array into a local variable first?

 ary := cA() B(ary[:]) 
+2
source

Source: https://habr.com/ru/post/902709/


All Articles