结构属性的动态标识符

huangapple go评论71阅读模式
英文:

Dynamic identifiers for struct properties

问题

一个用户有多个id字段 - 每种社交登录方式都有一个:

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

我有存储providerid的变量:

provider := "github" //也可以是facebook或google
id := "12345"

还有一个用户:

var user User
user.Name = "Bob"

但是我该如何将id分配给正确的属性呢?我尝试过:

if provider == "github" {
    field := "Github_id"
    user.field = id //还尝试了user[field] = id
}

但是目前还没有成功。

附加说明

我的用户可能有多个社交登录账户,所以我不能只使用一个social_id属性来解决这个问题。

英文:

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

得分: 2

在这种情况下,对结构体进行反射以填充正确的字段似乎有些过度。我建议在你的User结构体中添加一个映射字段来保存所有的社交ID。示例代码如下:

type User struct {
    Name string
    IDs  map[string]string
}

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

用法示例:

provider := "github" // 也可以是facebook或google
id := "12345"

user := NewUser()
user.Name = "Bob"
user.IDs[provider] = id

这样,你可以通过user.IDs映射来存储和访问不同社交平台的ID。

英文:

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

huangapple
  • 本文由 发表于 2016年1月6日 23:25:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/34636734.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定