struct/tag

This commit is contained in:
wandoubaba 2024-11-19 16:10:15 +08:00
parent 78173a1628
commit 952dcf9e12
2 changed files with 64 additions and 0 deletions

View 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)
}

View 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)
}