英文:
Dynamic identifiers for struct properties
问题
一个用户有多个id字段 - 每种社交登录方式都有一个:
type User struct {
Name string
Github_id string
Facebook_id string
Google_id string
}
我有存储provider
和id
的变量:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论