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

守候你守候我
TA貢獻(xiàn)1802條經(jīng)驗 獲得超10個贊
您無法在init()函數(shù)中打印令牌的值,因為該init()函數(shù)在第一次調(diào)用包時在運行時執(zhí)行。該值尚未分配。
因此,您必須全局聲明該變量并在命令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 關(guān)注
- 102 瀏覽
添加回答
舉報
0/150
提交
取消