os.args范例

package main

import "os"
import "fmt"
func main(){
args := os.Args // 得到args是一个[]string
fmt.Println("args:",args)
for i,v := range args{ // 循环得到每个空格参数的值,0是函数本身
fmt.Printf("args[%d] = %s\n",i ,v)
}
}
结果
(base) tommy@DESKTOP-2EIN43R:~/goproject/src/lyy910203/study/命令行参数$ ./main sd sdas asda sda sdasd asda sda sd asd
args: [./main sd sdas asda sda sdasd asda sda sd asd]
args[0] = ./main
args[1] = sd
args[2] = sdas
args[3] = asda
args[4] = sda
args[5] = sdasd
args[6] = asda
args[7] = sda
args[8] = sd
args[9] = asd

flag包,重要

package main

import "fmt"
import "flag"
func main(){
var confPath string // 定义接收的变量
var logLevel int
flag.StringVar(&confPath,"c","/etc/my.cnf","please input confPath")
// 参数定义 接收的变量 -c后面类容 默认参数 提示语
flag.IntVar(&logLevel,"l",0,"please input logLevel")
flag.Parse() // 调用这个参数才生效,之前是预处理
fmt.Println("confPath:",confPath)
fmt.Println("logLevel:",logLevel)
}
结果
(base) tommy@DESKTOP-2EIN43R:~/goproject/src/lyy910203/study/命令行参数$ ./main -l 20 -c sdasd
confPath: sdasd
logLevel: 20