golang命令行可以用两种方式实现,一个是用flag包,一个是用os包实现。

flag包

package main

import (
    "flag"
    "fmt"
)

var Name = flag.String("name", "Green", "input name")
var Age = flag.Int("age", 20, "input age")
var Marriage = flag.Bool("marriage", true, "input marriage")
var Job string

func Init() {
    flag.StringVar(&Job, "job", "Programmer", "input job")
}

func main() {
    Init()
    flag.Parse()

    fmt.Println("name=", *Name)
    fmt.Println("age=", *Age)
    fmt.Println("marriage=", *Marriage)
    fmt.Println("job=", Job)
}

以上代码编译后,执行。

D:\>flagLearn
name= Green
age= 20
marriage= true
job= Programmer

D:\>flagLearn -name Jack -age 30 -marriage=false -job Engineer
name= Jack
age= 30
marriage= false
job= Engineer

os包

package main
 
import (
    "fmt"
    "os"
)
 
func main() {
    fmt.Println(os.Args)
}