栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Go-复制结构之间的所有公共字段

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Go-复制结构之间的所有公共字段

这是使用反射的解决方案。如果您需要带有嵌入式结构字段等的更复杂的结构,则必须进一步开发它。

http://play.golang.org/p/iTaDgsdSaI

package mainimport (    "encoding/json"    "fmt"    "reflect")type M map[string]interface{} // just an aliasvar Record = []byte(`{ "bit_size": 8, "secret_key": false }`)type DB struct {    NumBits int  `json:"bit_size"`    Secret  bool `json:"secret_key"`}type User struct {    NumBits int `json:"num_bits"`}func main() {    d := new(DB)    e := json.Unmarshal(Record, d)    if e != nil {        panic(e)    }    m := mapFields(d)    fmt.Println("Mapped fields: ", m)    u := new(User)    o := applyMap(u, m)    fmt.Println("Applied map: ", o)    j, e := json.Marshal(o)    if e != nil {        panic(e)    }    fmt.Println("Output JSON: ", string(j))}func applyMap(u *User, m M) M {    t := reflect.TypeOf(u).Elem()    o := make(M)    for i := 0; i < t.NumField(); i++ {        f := t.FieldByIndex([]int{i})        // skip unexported fields        if f.PkgPath != "" { continue        }        if x, ok := m[f.Name]; ok { k := f.Tag.Get("json") o[k] = x        }    }    return o}func mapFields(x *DB) M {    o := make(M)    v := reflect.ValueOf(x).Elem()    t := v.Type()    for i := 0; i < v.NumField(); i++ {        f := t.FieldByIndex([]int{i})        // skip unexported fields        if f.PkgPath != "" { continue        }        o[f.Name] = v.FieldByIndex([]int{i}).Interface()    }    return o}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/452357.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号