簡體   English   中英

Go 反射陣列

[英]Go Reflect Array

結構如下:

type Auth_msg struct {
    Msg_class       [2]byte
    Msg_content_pty [2]byte

我剛開始在 Go 中使用 Reflect,我遇到了這個:

panic: reflect: call of reflect.Value.Bytes on array Value

當我運行val.Field(i).Bytes()時會發生這種情況,但是當我嘗試打印它時: fmt.PrintLn(val.Field(i)) ,它會打印出正確的 arrays。

我只是想知道,如何在數組或切片中檢索 Msg_class?

在Go中,有arrayslice的區別。 Value.Bytes()顯式僅適用於字節切片(文檔鏈接)。
注意:我不知道為什么它不處理字節 arrays; 它可能是這樣寫的,它使reflect.Bytes()的實現更簡單。 Anyway: slice 絕對是 Go 中的常見用例,並且很容易將數組轉換為 slice:


您可以使用[:]創建一個指向arrayslice

    v := reflect.ValueOf(msg.Msg_class)
    fmt.Println("kind :", v.Kind()) // prints 'array'
    // fmt.Printf("bytes : % x\n", v.Bytes())  // panics

    v = reflect.ValueOf(msg.Msg_class[:])
    fmt.Println("kind :", v.Kind())        // prints 'slice'
    fmt.Printf("bytes : % x\n", v.Bytes()) // works

https://play.golang.org/p/sKcGaru4rOq


要使用 reflect 將數組轉換為切片,您可以在reflect.Value上調用.Slice()

文檔中提到的一個約束是數組值必須是可尋址的。
我還沒有整理出所有細節,但確保反射值可尋址的一種方法是在指針上調用reflect.ValueOf() ,然后在該指針值上調用.Elem()

var arr [2]byte
arr[0] = 'g'
arr[1] = 'o'

// take ValueOf a *pointer* to your array, and let reflect dereference it :
v := reflect.ValueOf(&arr).Elem()
// this sets the "canAddr" flag on this value
fmt.Println("arr value - CanAddr() :", v.CanAddr()) // prints 'true'
slice := v.Slice(0, v.Len())
fmt.Printf("arr bytes : % x\n", slice.Bytes()) // prints '67 6f'

// for a field inside a struct : take a pointer to the struct
var msg Auth_msg
msg.Msg_class[0] = 'a'
msg.Msg_class[1] = 'z'

v = reflect.ValueOf(&msg).Elem()
fmt.Println("msg value - CanAddr() :", v.CanAddr()) // prints 'true'

// now reflect accepts to call ".Slice()" on one of its fields :
field := v.FieldByName("Msg_class")
slice = field.Slice(0, field.Len())
fmt.Printf("msg.Msg_class bytes : % x\n", slice.Bytes()) // prints '61 7a'

https://play.golang.org/p/SqM7yxl2D96

結構如下:

type Auth_msg struct {
    Msg_class       [2]byte
    Msg_content_pty [2]byte

我很新鮮在 Go 中使用反射,我遇到了這個:

panic: reflect: call of reflect.Value.Bytes on array Value

當我運行val.Field(i).Bytes()時會發生這種情況,但是當我嘗試打印它時: fmt.PrintLn(val.Field(i)) ,它會打印出正確的 arrays。

我只是想知道,如何在數組或切片中檢索 Msg_class?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM