【问题标题】:Golang language, combine some fields of anonymous structure?Golang语言,结合一些匿名结构的字段?
【发布时间】:2021-12-06 01:40:30
【问题描述】:

数据库实体、保留和数据映射。

type User struct{
        UserId int
        Org   int 
        Name string
        Password string
        Sex int 
        Age  int 
        Avatar string
 }
type Address struct{
     AddressId int 
     UserId int 
     Province int
     City int 
     District int
     Address int 
     Description string
}

在DAO中,我想对实体结构进行合并、剪切、扩展…… 例如:

      type UserInfo struct{
           User
           []Address
       }

但匿名结构是嵌入的,只能完整引用。如何引用一些字段?

    type UserInfo struct{
           User
           []Address

           Password string `json:"-"`
           Sex int `json:"-"`
           Age  int `json:"-"`
       }

【问题讨论】:

    标签: go struct embedding


    【解决方案1】:

    您不能“引用”某些字段。您可以嵌入(或使用常规字段)User,或者如果您不需要其所有字段,只需明确列出所需的字段即可。

    不要害怕重复 3 个字段。 Quoting Sandi Metz:

    复制比错误的抽象要便宜得多。

    如果您需要“太多”字段并且确实希望避免重复,您可以将这些字段放入另一个结构中,并将其嵌入到 UserUserInfo 中:

    type BaseUser struct {
        Password string `json:"-"`
        Sex      int    `json:"-"`
        Age      int    `json:"-"`
    }
    
    type User struct {
        BaseUser
    
        UserId int
        Org    int
        Name   string
        Avatar string
    }
    
    type UserInfo struct {
        BaseUser
        Addresses []Address
    }
    

    请注意,您可以在嵌入 BaseUser 时选择使用结构标记来将其从 JSON 编组中排除,而不是标记 BaseUser 的所有字段。

    【讨论】:

      【解决方案2】:

      你可以试试这个

      type UserInfo struct{
          User
          Addresses []Address
      
          Password string `json:"-"`
                 Sex int `json:"-"`
                 Age  int `json:"-"`
             }
      

      【讨论】:

      • 字段太多...
      猜你喜欢
      • 2014-10-21
      • 1970-01-01
      • 1970-01-01
      • 2015-02-23
      • 2015-11-22
      • 1970-01-01
      • 1970-01-01
      • 2018-01-20
      • 2014-01-14
      相关资源
      最近更新 更多