Defaults and Validation
Set sensible defaults.
Defaults and Validation is a free Go Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Go Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Set Sensible Defaults
A robust constructor starts from good defaults, then lets options override them. This avoids the zero-value trap entirely.
Initialize Before Applying
Build the config with defaults first, then apply the options on top.
package main
import "fmt"
type Server struct {
Port int
Timeout int
}
type Option func(*Server)
func WithPort(p int) Option { return func(s *Server) { s.Port = p } }
func NewServer(opts ...Option) *Server {
s := &Server{Port: 8080, Timeout: 30}
for _, o := range opts { o(s) }
return s
}
func main() {
fmt.Printf("%+v\n", *NewServer())
fmt.Printf("%+v\n", *NewServer(WithPort(9000)))
}Defaults Win Until Overridden
Calling with no options yields the defaults; an option replaces only the field it touches. Best of both worlds.
Validating After Apply
After applying options, validate the final config and return an error if it is invalid. Make the constructor return (*T, error).
package main
import (
"errors"
"fmt"
)
type Server struct{ Port int }
type Option func(*Server)
func WithPort(p int) Option { return func(s *Server) { s.Port = p } }
func NewServer(opts ...Option) (*Server, error) {
s := &Server{Port: 8080}
for _, o := range opts { o(s) }
if s.Port < 1 || s.Port > 65535 {
return nil, errors.New("invalid port")
}
return s, nil
}
func main() {
_, err := NewServer(WithPort(99999))
fmt.Println(err)
}Validation Inside Options
Alternatively, options themselves can return an error. The Option type becomes func(*Config) error.
package main
import (
"errors"
"fmt"
)
type Server struct{ Port int }
type Option func(*Server) error
func WithPort(p int) Option {
return func(s *Server) error {
if p < 1 {
return errors.New("port must be positive")
}
s.Port = p
return nil
}
}
func NewServer(opts ...Option) (*Server, error) {
s := &Server{Port: 8080}
for _, o := range opts {
if err := o(s); err != nil {
return nil, err
}
}
return s, nil
}
func main() {
_, err := NewServer(WithPort(-1))
fmt.Println(err)
}Which Validation Style
Validate in options for per-setting checks; validate after applying for cross-field rules (e.g. TLS requires a cert path). Often you use both.
Documenting Defaults
Always document each default in the constructor's doc comment so users know what they get when they omit an option.
Required vs Optional
Keep genuinely required values as positional parameters; reserve options for the truly optional. Do not hide required data behind an option.
package main
import "fmt"
type Client struct {
BaseURL string
Retries int
}
type Option func(*Client)
func WithRetries(n int) Option { return func(c *Client) { c.Retries = n } }
func NewClient(baseURL string, opts ...Option) *Client {
c := &Client{BaseURL: baseURL, Retries: 3}
for _, o := range opts { o(c) }
return c
}
func main() {
fmt.Printf("%+v\n", *NewClient("https://api"))
}Combining Options
You can compose several options into one preset for common configurations.
package main
import "fmt"
type Server struct{ Port, Timeout int }
type Option func(*Server)
func WithPort(p int) Option { return func(s *Server) { s.Port = p } }
func WithTimeout(t int) Option { return func(s *Server) { s.Timeout = t } }
func Production() Option {
return func(s *Server) {
WithPort(443)(s)
WithTimeout(60)(s)
}
}
func NewServer(opts ...Option) *Server {
s := &Server{Port: 8080, Timeout: 30}
for _, o := range opts { o(s) }
return s
}
func main() {
fmt.Printf("%+v\n", *NewServer(Production()))
}Best Practices
- Start from defaults, then apply options
- Validate after applying for cross-field rules
- Keep required values positional
- Document every default
A Complete, Robust API
Combining defaults, options, and validation gives you a constructor that is flexible, safe, self-documenting, and easy to extend.
Quick Check
Test your defaults and validation knowledge.
Recap
You completed the functional options pattern.
- Set defaults before applying options
- Validate after apply, or inside options for per-field checks
- Keep required values positional
- Compose options into presets, document defaults
Frequently asked questions
Is the “Defaults and Validation” lesson free?
Yes — the full text of “Defaults and Validation” is free to read here on the web, and the Go Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Go Academy course, upgrade to CoddyKit PRO.
What will I learn in “Defaults and Validation”?
Set sensible defaults. You practise Go Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Go Academy?
No prior experience is required. Go Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Defaults and Validation” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Go Academy lesson?
Yes. Every Go Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- The Problem with Many Params
- Option Functions
- Building a Flexible API
- Defaults and Validation