から行くの配列スライス私は、次の機能があります。関数returnステートメント
func (c *Class)A()[4]byte
func B(x []byte)
私は
B(c.A()[:])
を呼びたいが、私はこのエラーを取得:
cannot take the address of c.(*Class).A()
私はどのようにGoの関数で返された配列のスライスを適切に取得しますか?
から行くの配列スライス私は、次の機能があります。関数returnステートメント
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