英文:
Creating sub-commands with the same name in Go w/ Cobra
问题
我对Go和Cobra都非常陌生,这是我在Cobra中的第一个项目。
使用Cobra命令行工具创建命令似乎很容易:
cobra add <command>
添加子命令也很简单:
cobra add <subcommand> -p '<command>'
然而,我遇到的问题是为两个不同的命令添加两个同名的子命令。例如:
我可能有一个名为'people'的命令和一个名为'places'的命令。
cobra add people
cobra add places
每个命令都需要自己的名为'add'的子命令。
cobra add add -p 'people'
cobra add add -p 'places'
第二个命令会失败,因为它会尝试创建一个已经被第一个命令创建的'add.go'文件。是否有可能为不同的父命令添加同名的子命令?最终的结果会是这样的:
people add --first "bob" --last "smith"
places add "someplace" --zip "12345"
英文:
I'm very new to Go in general, and this is my first project in Cobra.
It seems easy enough to create commands in Cobra with the command-line tool:<br/>
cobra add <command>
And adding sub-commands seems easy enough as well.<br/>
cobra add <subcommand> -p '<command>'
Where I've run into an issue is having two sub-commands for two different commands, but having the sub-commands have the same name. For instance:
I may have a command named 'people' and a command named 'places'.<br/>
cobra add people
<br/>
cobra add places
Each command needs its own sub-command called 'add'.<br/>
cobra add add -p 'people'
<br/>
cobra add add -p 'places'
The second command will fail because it will attempt to create an 'add.go' file which was already created by the first command. Is it possible to add sub-commands of the same name to different parent commands? Where the end result would be something like:<br/>
people add --first "bob" --last "smith"
<br/>
places add "someplace" --zip "12345"
答案1
得分: 2
command add
的作用只是为您生成一个Go源文件。您可以自己编写文件,或者您可以使用第一个创建的文件,将其重命名,然后创建下一个文件。您还可能需要重命名生成文件中的一些全局变量/函数,以避免名称冲突。
英文:
All command add
does is generate a Go source file for you. You could write the file yourself; or you could take the first one that was created, rename it, then create the next one. You'll also likely have to rename some global variables/functions in the generated files to avoid name collisions.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论