如何从命令对象传递参数

I use the following code which need to pass value from functions root, value

var cfBuild = &cobra.Command{
    Use:   "build",
    Short: "Build",
    Run: func(cmd *cobra.Command, args []string) {


        root, value := Build(target)
    },
    PersistentPostRun: func(cmd *cobra.Command, args []string) {
   //Here I need to use root, value
   } 
}

I can do it by using global variable but is there a nice way to avoid global in this case ?

This is the repo, I didnt find any nice way to do it ... https://github.com/spf13/cobra

Btw there is option to use viper

like ...

Run: func(cmd *cobra.Command, args []string) {
    root, value := Build(target)
    viper.Set("root", root)
    viper.Set("value", value)

and then get it in the other method... Is it good direction?

you don't need Viper for that. Just create 2 singletons (variables with global scope in the command file) and you can assign them to your Build function returns.

Example

package cmd

var (
    root,
    value string
)

var cfBuild = &cobra.Command{
    Use:   "build",
    Short: "Build",
    Run: func(cmd *cobra.Command, args []string) {
        root, value = Build(target)
    },
    PersistentPostRun: func(cmd *cobra.Command, args []string) {
        fmt.Printf("%s, %s", root, value)
   } 
}