参考:https://www.cnblogs.com/mayanan/p/15414957.html
package main
import (
"fmt"
"os"
)
func main() {
// 执行:./demo.exe 127.0.0.1 8000
// 输出切片类型:[C:\Users\mayanan\Desktop\pro_go\day01\demo.exe 127.0.0.1 8000]
fmt.Println(os.Args)
}
package main
import (
"flag"
"fmt"
)
func main() {
//fmt.Println(os.Args)
// 如果想支持 ./demo.exe -h 127.0.0.1 -p 8080 则需要使用flag模块来进行处理
// 定义方式1
host := flag.String("h", "127.0.0.1", "主机")
port := flag.Int("p", 8000, "端口")
// 定义方式2
var email string
flag.StringVar(&email, "e", "myn_net@163.com", "邮箱")
flag.Parse()
fmt.Println(*host, *port, email)
// 构建方法: go build -o demo.exe -o可以指定构建成的文件名称
// 执行方法
// ./demo.exe -h 192.168.1.1 -p 8888 -e 1341935532@qq.com 输出:192.168.1.1 8888 1341935532@qq.com
// ./demo.exe -h=192.168.1.1 -p=8888 -e=1341935532@qq.com
// 或者使用默认值:直接./demo.exe 输出默认值:127.0.0.1 8000 myn_net@163.com
}
转载请注明:liutianfeng.com » golang-参数传入