我使用https://github.com/spf13/cobra庫創建了一個小型 Go 應用程序。我創建了一個新標志-tor?--token,當我傳遞這個參數時,我希望應用程序打印它。這就是我所做的:func?init()?{
????fmt.Println("[*]?Inside?init()")
????????var?token?string
????rootCmd.PersistentFlags().StringVarP(&token,?"token",?"t",?"",?"Service?account?Token?(JWT)?to?insert")
????fmt.Println(token)
}但當我像這樣運行應用程序時它不會打印它:.\consoleplay.exe?--token?"hello.token"如何打印標志的值。
1 回答

守候你守候我
TA貢獻1802條經驗 獲得超10個贊
您無法在init()函數中打印令牌的值,因為該init()函數在第一次調用包時在運行時執行。該值尚未分配。
因此,您必須全局聲明該變量并在命令Run的方法中使用它rootCmd。
var token string
var rootCmd = &cobra.Command{
Use: "consoleplay",
Run: func(cmd *cobra.Command, args []string) {
fmt.Println(token)
},
}
func init() {
rootCmd.Flags().StringVarP(&token, "token", "t", "", "usage")
}
- 1 回答
- 0 關注
- 119 瀏覽
添加回答
舉報
0/150
提交
取消