Go-15-flag.String 获取系统参数

场景:

启动应用程序时,需要传入系统参数。例如:./start --b /notebook --p true --n 8

package main

import (
    "fmt"
    flag "github.com/spf13/pflag"
)

func main() {
    home_dir:= flag.String("b","/home/default_dir","home path") 
    isProdEnvironment:= flag.Bool("p", false,"environment is pord")
    int_value:= flag.Int("n",2, "pod num")

    flag.Parse()

    fmt.Println("backup_dir:",*home_dir)
    fmt.Println("isProdEnvironment",*isProdEnvironment)
    fmt.Println("int_value",*int_value)
}

运行结果:

D:GoWorkspacemy-go-code	est>go run Test8.go --b "/home/back" --p true --n 8
backup_dir: /home/back
isProdEnvironment true
int_value 8

D:GoWorkspacemy-go-code	est>

其中:

// String defines a string flag with specified name, default value, and usage string.
// The return value is the address of a string variable that stores the value of the flag.
func String(name string, value string, usage string) *string {
    return CommandLine.StringP(name, "", value, usage)
}
原文地址:https://www.cnblogs.com/shix0909/p/12968477.html