GO語言"reflect"包中"StructOf"函數的用法及代碼示例。
用法:
func StructOf(fields []StructField) Type
StructOf 返回包含字段的結構類型。 Offset 和 Index 字段將被編譯器忽略和計算。
StructOf 當前不會為嵌入字段生成包裝方法,如果未導出傳遞,則會出現Panics StructFields 這些限製可能會在未來版本中取消。
例子:
package main
import (
"bytes"
"encoding/json"
"fmt"
"reflect"
)
func main() {
typ := reflect.StructOf([]reflect.StructField{
{
Name: "Height",
Type: reflect.TypeOf(float64(0)),
Tag: `json:"height"`,
},
{
Name: "Age",
Type: reflect.TypeOf(int(0)),
Tag: `json:"age"`,
},
})
v := reflect.New(typ).Elem()
v.Field(0).SetFloat(0.4)
v.Field(1).SetInt(2)
s := v.Addr().Interface()
w := new(bytes.Buffer)
if err := json.NewEncoder(w).Encode(s); err != nil {
panic(err)
}
fmt.Printf("value: %+v\n", s)
fmt.Printf("json: %s", w.Bytes())
r := bytes.NewReader([]byte(`{"height":1.5,"age":10}`))
if err := json.NewDecoder(r).Decode(s); err != nil {
panic(err)
}
fmt.Printf("value: %+v\n", s)
}
輸出:
value: &{Height:0.4 Age:2} json: {"height":0.4,"age":2} value: &{Height:1.5 Age:10}
相關用法
- GO StructTag.Lookup用法及代碼示例
- GO StructTag用法及代碼示例
- GO StreamWriter用法及代碼示例
- GO Strings用法及代碼示例
- GO Stringer用法及代碼示例
- GO StripPrefix用法及代碼示例
- GO StreamReader用法及代碼示例
- GO Stmt用法及代碼示例
- GO Stmt.QueryRowContext用法及代碼示例
- GO Scanner.Scan用法及代碼示例
- GO Split用法及代碼示例
- GO Server.Shutdown用法及代碼示例
- GO Slice用法及代碼示例
- GO SplitAfter用法及代碼示例
- GO Sum256用法及代碼示例
- GO SectionReader用法及代碼示例
- GO Sin用法及代碼示例
- GO Sprintf用法及代碼示例
- GO SendMail用法及代碼示例
- GO Sprint用法及代碼示例
注:本文由純淨天空篩選整理自golang.google.cn大神的英文原創作品 StructOf。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。