#I need help to reduce struct field repeat in methods ?

6 messages · Page 1 of 1 (latest)

fresh arrow
#

`package main

import "fmt"

type User struct {
Name string
IsActive bool
Roll int
}

func NewUser() *User {
user := new(User)
return user
}

func (u *User) SetName(v string) *User {

return &User{Name: v, Roll: u.Roll, IsActive: u.IsActive}

}
func (u *User) SetIsActive(v bool) *User {
return &User{Name: u.Name, Roll: u.Roll, IsActive: v}
}
func (u *User) SetRoll(v int) *User {
return &User{Name: u.Name, Roll: v, IsActive: u.IsActive}
}

func main() {

user := NewUser().SetIsActive(true).SetName("harsh").SetRoll(69)

fmt.Println(user)

}`

stiff heron
#

consider just using a struct literal

fickle island
#
func (u *User) SetName(name string) *User {
        u.Name = name
        return u
}

should suffice too
tbh I haven't seen the builder pattern being used in Go programs much

bronze temple
#

If you're going to be creating a brand new User each time, there is no reason to have a pointer receiver, or to return a pointer.
If you want to mutate the object, MoyenGopher has the right idea.

dense pewter
#

Builder pattern in go is not needed. Your fields are exported ...
use them instead of creating useless functions

sharp edge
#

@dense pewter I'm not familiar with the builder pattern. Can you summarize what op is doing here that makes his code follow the builder pattern?