英文:
Is it possible to use mass assignment in golang?
问题
我有一个这样的结构体:
type User struct {
Id uint64
Email string
}
我知道,我可以这样声明它:
user := User{
Id: 1,
Email: "test@example.com",
}
我可以这样更新它:
user.Id = 2
user.Email = "test1@example.com"
是否可以使用类似的结构来更新结构体?
英文:
I have my struct like this:
type User struct {
Id uint64
Email string
}
And I know, that I can declare it like this:
user := User{
Id: 1,
Email: "test@example.com",
}
And I can update it like this:
user.Id = 2
user.Email = "test1@example.com"
Is it possible to use similar construction like for creating but for updating struct?
答案1
得分: 2
不,实际上没有一个等效的多属性设置器。
编辑:
可能通过反射可以做到类似以下的操作:
updates := user := User{
Email: "newemail@example.com",
}
//通过反射(伪代码)
对于目标对象中的每个字段 {
如果 updates.field 不是零值 {
设置 target.field = updates.field
}
}
反射部分可以封装成一个函数 updateFields(dst, src interface{})
,但我通常会说这种复杂性不值得节省。只需逐个设置几行字段即可。
英文:
No, there really isn't an equivalent multi-property setter.
EDIT:
Possibly with reflection you could do something like:
updates := user := User{
Email: "newemail@example.com",
}
//via reflection (pseudo code)
for each field in target object {
if updates.field is not zero value{
set target.field = updates.field
}
}
The reflection part could be factored into a function updateFields(dst, src interface{})
, but I would generally say the complexity is not worth the savings. Just have a few lines of setting fields one by one.
答案2
得分: 1
这是要翻译的内容:
这不是完全相同的,但你可以使用多值返回功能在一行中设置它们。
package main
import (
"fmt"
)
type User struct {
Id uint64
Email string
Name string
}
func main() {
user := User{
Id: 1,
Email: "test@example.com",
Name: "Peter",
}
fmt.Println(user)
user.Id, user.Email = 2, "also-test@example.com"
fmt.Println(user) // user.Name = "Peter"
}
英文:
It's not the same, but you can use the multivalue return functionality to set them in one line.
https://play.golang.org/p/SGuOhdJieW
package main
import (
"fmt"
)
type User struct {
Id uint64
Email string
Name string
}
func main() {
user := User{
Id: 1,
Email: "test@example.com",
Name: "Peter",
}
fmt.Println(user)
user.Id, user.Email = 2, "also-test@example.com"
fmt.Println(user) // user.Name = "Peter"
}
答案3
得分: 0
你是这样的意思吗?
package main
import (
"fmt"
)
type User struct {
Id uint64
Email string
}
func main() {
user := User{
Id: 1,
Email: "test@example.com",
}
fmt.Println(user)
user = User{
Id: 2,
Email: "also-test@example.com",
}
fmt.Println(user)
}
链接:https://play.golang.org/p/5-ME3p_JaV
英文:
Do you mean like this?
package main
import (
"fmt"
)
type User struct {
Id uint64
Email string
}
func main() {
user := User{
Id: 1,
Email: "test@example.com",
}
fmt.Println(user)
user = User{
Id: 2,
Email: "also-test@example.com",
}
fmt.Println(user)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论