我有以下功能:轉到陣列片
func (c *Class)A()[4]byte
func B(x []byte)
我想打電話給
B(c.A()[:])
,但我得到這個錯誤:
cannot take the address of c.(*Class).A()
我如何在Go中正確地獲取由函數返回的數組的切片?
我有以下功能:轉到陣列片
func (c *Class)A()[4]byte
func B(x []byte)
我想打電話給
B(c.A()[:])
,但我得到這個錯誤:
cannot take the address of c.(*Class).A()
我如何在Go中正確地獲取由函數返回的數組的切片?
c.A()
的值,來自方法的返回值不可尋址。
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.
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]
你有沒有試過先在本地變量中粘貼數組?
ary := c.A()
B(ary[:])
是的,但是當我想調用20只起到這樣的,每一個用於一個不同的陣列的長度,我必須使一個新的數組每次這樣的呼叫。我希望有一個更好的解決方案。 – ThePiachu
@ThePiachu:爲什麼函數返回一個數組?他們爲什麼不返回數組的一部分? – peterSO
@peterSO因爲它們返回的數據存儲在一個具有固定大小的數組中的對象中。我想我也可以使另一個函數返回一個數組的切片。 – ThePiachu