2011-11-29 17 views
6

aşağıdaki işlevlere sahiptir:Git dizi dilim

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

Ben

B(c.A()[:]) 

çağırmak istiyorum ama bu hatayı alıyorum:

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

Nasıl yaparım Go'da bir işlev tarafından döndürülen bir dizi bir diziyi düzgün bir şekilde alsın mı?

cevap

8

c.A() değeri, bir yöntem ile döner, adreslenebilir değildir.

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.

dilim işlemi [:] için c.A() değerini, bir dizi, adreslenebilir olun. Örneğin, değeri bir değişkene atayın; Bir değişken adreslenebilir. Örneğin

,

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

Çıktı:

x [0 1 2 3] 
2

Diziyi önce yerel bir değişkene yapıştırmayı denediniz mi?

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

Evet, ama farklı bir dizi uzunluğu için böyle 20 fonksiyonları, her görüşme yapmak istediğinizde, ben yeni bir dizi yapmak Her böyle bir çağrı. Daha iyi bir çözüm olacağını umuyorum. – ThePiachu

+0

@ThePiachu: Neden bir dizi döndüren işlevler var? Neden dizinin bir dilimine dönmüyorlar? – peterSO

+0

@peterSO Döndükleri veriler sabit boyutlu bir dizide bir nesnede depolandığından. Sanırım bunun yerine bir dizinin bir dilimini döndürecek başka işlevler de yapabilirim. – ThePiachu

İlgili konular