How to Chain Methods in Go (Fluent Interface)

Go requires explicit pointer returns in methods to enable manual method chaining, as it lacks native fluent interface support.

Go does not support method chaining (fluent interfaces) natively because methods cannot return self by default without explicit receiver types, and the language philosophy discourages this pattern in favor of explicit error handling and clarity. To achieve chaining, you must define methods that return a pointer to the receiver type, allowing subsequent calls on the returned value.

type Builder struct {
    name string
}

func (b *Builder) SetName(n string) *Builder {
    b.name = n
    return b
}

func (b *Builder) Build() string {
    return b.name
}

// Usage
result := (&Builder{}).SetName("test").Build()