Skip to content

Instantly share code, notes, and snippets.

@dlisboa
Created August 8, 2024 13:09
Show Gist options
  • Select an option

  • Save dlisboa/8a7aac51a4febead32827d88c7995c9b to your computer and use it in GitHub Desktop.

Select an option

Save dlisboa/8a7aac51a4febead32827d88c7995c9b to your computer and use it in GitHub Desktop.
Option struct with default values
package main
import (
"fmt"
"time"
)
type Config struct {
Timeout time.Duration
Name string
}
// this uses a pointer to allow it to be changed before use
func (c *Config) init() {
if c.Timeout == 0 {
c.Timeout = 10 * time.Second
}
if c.Name == "" {
c.Name = "default name"
}
}
func (c Config) String() string {
return fmt.Sprintf("using %q with %s timeout", c.Name, c.Timeout)
}
// this allows c to be just a stack value and not a pointer
// the Config c will be gone right after using it
func use(c Config) {
c.init()
fmt.Println(c)
}
func main() {
cfg := Config{}
use(cfg)
// simple struct creation, not taking a pointer to it
cfg2 := Config{Name: "some other name"}
use(cfg2)
cfg3 := Config{Name: "yet another name", Timeout: 3 * time.Second}
use(cfg3)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment