2011-11-29 6 views
6

나는 다음과 같은 기능이 있습니다이동 배열 슬라이스

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

내가

B(c.A()[:]) 

를 호출 할을하지만 난이 오류를 얻을 :

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

어떻게 할을 제대로 Go에 함수가 반환 한 배열 조각을 얻으시겠습니까?

답변

8

c.A()의 값은 방법의 반환 값은 어드레싱 아니다.

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.

슬라이스 동작 [:] 대한 c.A()의 값을 배열 드레서합니다. 예를 들어, 값을 변수에 할당하십시오. 변수가 지정 가능합니다. 예를 들어

,

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

출력 :

x [0 1 2 3] 
2

먼저 로컬 변수에 배열을 고정 시키려고 했습니까?

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

네,하지만 나는 다른 배열 길이 같은 20 개 기능, 각 호출 할 때, 내가 가지고있는가에 대한 새로운 배열을 만들 각각의 전화. 나는 깔끔한 해결책이 있기를 바랐다. – ThePiachu

+0

@ ThePiachu : 함수가 배열을 반환하는 이유는 무엇입니까? 배열의 일부를 반환하지 않는 이유는 무엇입니까? – peterSO

+0

@peterSO 반환하는 데이터는 고정 된 크기의 배열에있는 객체에 저장되기 때문에. 나는 또한 배열의 조각을 대신 반환하는 다른 함수를 만들 수 있다고 생각한다. – ThePiachu