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]
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
@ThePiachu: Dlaczego funkcje zwracają tablicę? Dlaczego nie zwracają kawałka tablicy? – peterSO
@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