How to Implement the Builder Pattern in Go

Implement the Builder Pattern in Go using a struct with pointer receivers and chaining setter methods that return the builder instance.

Implement the Builder Pattern in Go by defining a struct with a pointer receiver and chaining setter methods that return the builder itself.

type User struct {
	Name string
	Age  int
}

type UserBuilder struct {
	u User
}

func NewUserBuilder() *UserBuilder {
	return &UserBuilder{}
}

func (b *UserBuilder) WithName(name string) *UserBuilder {
	b.u.Name = name
	return b
}

func (b *UserBuilder) WithAge(age int) *UserBuilder {
	b.u.Age = age
	return b
}

func (b *UserBuilder) Build() User {
	return b.u
}

// Usage:
// user := NewUserBuilder().WithName("Alice").WithAge(30).Build()