简体   繁体   中英

Is it possible to use mass assignment in golang?

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?

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.

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"

}

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)
}

https://play.golang.org/p/5-ME3p_JaV

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM