【go语言】命令行参数
专栏:web开发笔记 April 14, 2025, 2:22 p.m. 63 阅读
用标准库flag来处理命令行参数

下面是一个go标准库flag的简单示例。演示了布尔型、字符串型、数字型参数的定义方法。

// File: get_arg.go

package main

import "fmt"
import "flag"

func main(){
     //bool型
     name := flag.String("name", //名称
	 					 "nick", //default值
						 "Input your name" //提示词
						 )
     //字符串型
     age := flag.Int("age", 28, "Input your age")
     //数字型
     isStudent := flag.Bool("isStudent", false, "Is student")

     //调用parse来解析命令行参数
     flag.Parse()

     //打印结果
     fmt.Printf("name=%s\n", *name)
     fmt.Printf("age=%d\n", *age)
     fmt.Print("isStudent=", *isStudent, "\n")
}

执行后打印结果如下:

go run get_arg.go -name abc -age 23
# name=abc
# age=23
# isStudent=false

当指定了没有定义的参数会提示没有定义。

go run get_arg.go -name abc -age 23 -gender male
flag provided but not defined: -gender

布尔型的参数,就是没有值的参数。默认值一般设成false,当命令行给了参数后,就变为true

go run getarg.go -isStudent
name=nick
age=28
isStudent=true

参数形式支持=或者空格

go run get_arg.go -name abc -age 23
go run get_arg.go -name=abc -age=23

-h-help--help可以打印出参数使用方法:

go run getarg.go -help
  -age int
    	Input your age (default 28)
  -isStudent
    	Is student
  -name string
    	Input your name (default "nick")

参考文档:

 

感谢阅读,更多文章点击这里:【专栏:web开发笔记】
最新20篇 开设专栏