struct/tag
This commit is contained in:
parent
78173a1628
commit
952dcf9e12
27
bilibili/aceld/struct/tag/test.go
Normal file
27
bilibili/aceld/struct/tag/test.go
Normal file
@ -0,0 +1,27 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"reflect"
|
||||
)
|
||||
|
||||
type resume struct {
|
||||
Name string `info:"name" doc:"我的名字"`
|
||||
Sex string `info:"sex" doc:"我的性别,接收male或者female"`
|
||||
}
|
||||
|
||||
func findTag(str interface{}) {
|
||||
t := reflect.TypeOf(str).Elem()
|
||||
|
||||
for i := 0; i < t.NumField(); i++ {
|
||||
taginfo := t.Field(i).Tag.Get("info")
|
||||
tagdoc := t.Field(i).Tag.Get("doc")
|
||||
fmt.Println("info: ", taginfo)
|
||||
fmt.Println("doc: ", tagdoc)
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
var re resume
|
||||
findTag(&re)
|
||||
}
|
37
bilibili/aceld/struct/tag2/test.go
Normal file
37
bilibili/aceld/struct/tag2/test.go
Normal file
@ -0,0 +1,37 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// type Movie struct {
|
||||
// Title string `json:"title"`
|
||||
// Year int `json:"year"`
|
||||
// Price int `json:"rmb"`
|
||||
// Actors []string `json:"actors"`
|
||||
// }
|
||||
|
||||
type Movie struct {
|
||||
Title string
|
||||
Year int
|
||||
Price int
|
||||
Actors []string
|
||||
}
|
||||
|
||||
func main() {
|
||||
movie := Movie{"喜剧之王", 2000, 10, []string{"xingye", "zhangbozhi"}}
|
||||
jsonStr, err := json.Marshal(movie)
|
||||
if err != nil {
|
||||
fmt.Println("json marshal error", err)
|
||||
return
|
||||
}
|
||||
fmt.Printf("jsonStr = %s\n", jsonStr)
|
||||
myMovie := Movie{}
|
||||
json.Unmarshal(jsonStr, &myMovie)
|
||||
if err != nil {
|
||||
fmt.Println("json unmarshal failed", err)
|
||||
return
|
||||
}
|
||||
fmt.Printf("%v\n", myMovie)
|
||||
}
|
Loading…
Reference in New Issue
Block a user