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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害