douxiong5972 2016-01-06 15:25
浏览 19
已采纳

结构属性的动态标识符

A user has a number of id fields - one for each type of social login:

type User struct {
    Name         string
    Github_id    string
    Facebook_id  string
    Google_id    string
}

I have variables that store the provider and id:

provider := "github" //could be facebook or google too
id := "12345"

and a user:

var user User
user.Name = "Bob"

but how can I assign the id to the correct property? I've tried:

if provider == "github" {
    field := "Github_id"
    user.field = id //and also user[field] = id
}

but no success so far.

Additional Note

My users may have multiple social login accounts so I can't just use a single social_id property as a solution to this problem.

  • 写回答

1条回答 默认 最新

  • duansha7453 2016-01-06 15:35
    关注

    Performing reflection on the struct in order to fill-in the correct field seems like overkill, in this case.

    I would recommend having a map field in your User struct to hold all of the social IDs. Example:

    type User struct {
        Name string
        IDs  map[string]string
    }
    
    func NewUser() *User {
       return &User{
           IDs: make(map[string]string),
       }
    }
    

    Usage:

    provider := "github" // could be facebook or google too
    id := "12345"
    
    user := NewUser()
    user.Name = "Bob"
    user.IDs[provider] = id
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)