您可以使用存储在Name变量中的值在程序中执行操作。cobra 的一个示例用法是:
var Name = "sample_"
var rootCmd = &cobra.Command{
Use: "hello",
Short: "Example short description",
Run: func(cmd *cobra.Command, args []string) {
// Do Stuff Here
},
}
var echoCmd = &cobra.Command{
Use: "echo",
Short: "Echo description",
Run: func(cmd *cobra.Command, args []string) {
fmt.Printf("hello %s", Name)
},
}
func init() {
rootCmd.AddCommand(echoCmd)
}
func Execute() {
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
`
在上面的代码中,您可以看到它hello是根命令,echo是子命令。如果你这样做hello echo,它将回显sample_存储在Name变量中的值。
你也可以这样做:
var echoCmd = &cobra.Command{
Use: "echo",
Short: "Echo description",
Run: func(cmd *cobra.Command, args []string) {
// Perform some logical operations
if Name == "sample_" {
fmt.Printf("hello %s", Name)
} else {
fmt.Println("Name did not match")
}
},
}
要了解有关如何使用 cobra 的更多信息,您还可以从以下链接查看我的项目。
https://github.com/bharath-srinivas/nephele
希望这可以帮助。