Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go array slice from function return statement

Tags:

slice

return

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?

like image 381
ThePiachu Avatar asked Nov 29 '11 22:11

ThePiachu


1 Answers

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]
like image 53
peterSO Avatar answered Oct 16 '22 21:10

peterSO