github.com/grailbio/base@v0.0.11/config/cmd/demosuggestimpl/main.go (about)

     1  package main
     2  
     3  import (
     4  	"flag"
     5  	"fmt"
     6  
     7  	"github.com/grailbio/base/config"
     8  	"github.com/grailbio/base/must"
     9  )
    10  
    11  type (
    12  	Fruit  interface{ IsFruit() }
    13  	Apple  struct{ color string }
    14  	Orange struct{}
    15  )
    16  
    17  func (Apple) IsFruit()  {}
    18  func (Orange) IsFruit() {}
    19  
    20  func init() {
    21  	config.Register("fruits/apple-red", func(c *config.Constructor[Apple]) {
    22  		c.Doc = "Some people like apples."
    23  		c.New = func() (Apple, error) { return Apple{"red"}, nil }
    24  	})
    25  	config.Register("fruits/apple-green", func(c *config.Constructor[Apple]) {
    26  		c.Doc = "Another apple."
    27  		c.New = func() (Apple, error) { return Apple{"green"}, nil }
    28  	})
    29  	config.Register("fruits/orange", func(c *config.Constructor[Orange]) {
    30  		c.Doc = "Some people like oranges."
    31  		c.New = func() (Orange, error) { return Orange{}, nil }
    32  	})
    33  	config.Register("favorite", func(c *config.Constructor[Fruit]) {
    34  		c.Doc = "My favorite fruit."
    35  		var favorite Fruit
    36  		c.InstanceVar(&favorite, "is", "favorite-apple", "Favorite fruit?")
    37  		c.New = func() (Fruit, error) { return favorite, nil }
    38  	})
    39  	config.Register("favorite-apple", func(c *config.Constructor[Apple]) {
    40  		c.Doc = "My favorite apple."
    41  		var favorite Apple
    42  		c.InstanceVar(&favorite, "is", "fruits/apple-green", "Favorite apple?")
    43  		c.New = func() (Apple, error) { return favorite, nil }
    44  	})
    45  }
    46  
    47  func main() {
    48  	config.RegisterFlags("", "")
    49  	flag.Parse()
    50  	must.Nil(config.ProcessFlags())
    51  
    52  	var fruit Fruit
    53  	must.Nil(config.Instance("favorite", &fruit))
    54  	fmt.Printf("My favorite fruit is %#v.\n", fruit)
    55  
    56  	var apple Apple
    57  	must.Nil(config.Instance("favorite-apple", &apple))
    58  	fmt.Printf("My favorite apple is %#v.\n", apple)
    59  }