// 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} }
Those above code is very easy to understand, we need to split it into perspective
when we directly instantiate a class, if the brace row vertically, then after members inside the assignment to add a comma
B: = Taoshihan { Name: "taoshihan", } fmt.Println(b.Name)
Define an interface, the interface inside a member method
type Flag interface { GetName() string }
Define another type, which happens to have this method, then you can think that this type implements the interface
type StringFlag struct { } func (t StringFlag) GetName() string { return "taoshihan" }
Flag this time if you define the type of variable, StringFlag also be assigned in the past
was a Flag a = StringFlag{} a.GetName()
Then back to the original logic of the code, using the following if this is very easy to understand manner
was myflag [] Flag myflag = append(myflag, StringFlag{}, StringFlag{}) command := Command{ Flags: myflag, }
Complete source code:
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) was myflag [] Flag myflag = append(myflag, StringFlag{}, StringFlag{}) command := Command{ Flags: myflag, } for _, p := range command.Flags { fmt.Println(p.GetName()) } }