2011-11-29 14 views
6

Mam następujące funkcje:Go plaster tablicę z instrukcji return funkcja

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

chcę zadzwonić

B(c.A()[:]) 

ale otrzymuję ten błąd:

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

jak mogę poprawnie uzyskać fragment tablicy zwróconej przez funkcję w Go?

Odpowiedz

8

Wartość c.A() wartość powrotna z metodą, nie może być adresowany.

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.

Bądź wartość c.A(), tablicę, adresowalnych dla operacji slice [:]. Na przykład przypisz wartość do zmiennej; zmienna jest adresowalna.

Na przykład

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[:]) 
} 

wyjściowa:

x [0 1 2 3] 
2

Czy próbowałeś najpierw umieścić tablicę w zmiennej lokalnej?

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

Tak, ale gdy chcę zadzwonić 20 działa tak, każdy dla innej długości tablicy, muszę zrobić nową tablicę dla każde takie połączenie. Miałem nadzieję, że będzie lepsze rozwiązanie. – ThePiachu

+0

@ThePiachu: Dlaczego funkcje zwracają tablicę? Dlaczego nie zwracają kawałka tablicy? – peterSO

+0

@peterSO Ponieważ dane, które zwracają są przechowywane w obiekcie w tablicy o stałym rozmiarze. Sądzę, że mógłbym również utworzyć inne funkcje, które zamiast tego zwrócą kawałek tablicy. – ThePiachu

Powiązane problemy