// getCommands func getCommands() []cli.Command { command := cli.Command{ Name: "web", Usage: "run web server", Action: runWeb, Flags: []cli.Flag{ cli.StringFlag{ Name: "host", Value: "0.0.0.0", Usage: "bind host", }, cli.IntFlag{ Name: "port,p", Value: DefaultPort, Usage: "bind port", }, cli.StringFlag{ Name: "env,e", Value: "prod", Usage: "runtime environment, dev|test|prod", }, }, } return []cli.Command{command} }
The above code is not easy to understand. We need to break it up
When we instantiate a class directly, if the braces are arranged vertically, a comma should be added after the member assignment.
b := Taoshihan{ Name: "taoshihan", } fmt.Println(b.Name)
Define an interface with a member method
type Flag interface { GetName() string }
If you define another type that just has this method, you can think that this type implements the interface
type StringFlag struct { } func (t StringFlag) GetName() string { return "taoshihan" }
At this time, if you define variables of Flag type, StringFlag can also be assigned to the past
var a Flag a = StringFlag{} a.GetName()
Back to the logic in the original code, it's easy to understand if you use the following method
var myflag []Flag myflag = append(myflag, StringFlag{}, StringFlag{}) command := Command{ Flags: myflag, }
Full source:
package main import "fmt" type Flag interface { GetName() string } type Command struct { Flags []Flag } type StringFlag struct { } func (t StringFlag) GetName() string { return "taoshihan" } type Taoshihan struct { Name string } func main() { // var a Flag // a = StringFlag{} // a.GetName() // b := Taoshihan{ // Name: "taoshihan", // } // fmt.Println(b.Name) var myflag []Flag myflag = append(myflag, StringFlag{}, StringFlag{}) command := Command{ Flags: myflag, } for _, p := range command.Flags { fmt.Println(p.GetName()) } }