8

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?

2 Answers 2

10

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] 
Sign up to request clarification or add additional context in comments.

Comments

2

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

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

4 Comments

Yes, but when I want to call 20 functions like that, each for a different array length, I have to make a new array for each such call. I hoped there would be a neater solution.
@ThePiachu: Why are the functions returning an array? Why aren't they returning a slice of the array?
@peterSO Because the data they return is stored in an object in an array with fixed size. I guess I could also make another functions that would return a slice of an array instead.
@ThePiachu If you return the array, you will end up copying the entire array for each function. If you return a slice, the return value will simply copy the slice struct which has a reference to the original array. For small arrays, not a big deal, but could be expensive.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.