1

在Go语言中构建命令行

 1 year ago
source link: https://sunqi.site/posts/old-sun-learning-go-notes-8-2/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

在Go语言中构建命令行

 2023-01-05  约 217 字   预计阅读 1 分钟    次阅读  

命令行也是应用开发时必不可少的作用,命令行的样式相对比较统一,Go中提供了flag包用于定义命令行参数。

package main

import (
    "flag"
    "fmt"
)

func main() {

    wordPtr := flag.String("word", "foo", "a string")

    numbPtr := flag.Int("numb", 42, "an int")
    forkPtr := flag.Bool("fork", false, "a bool")

    var svar string
    flag.StringVar(&svar, "svar", "bar", "a string var")

    flag.Parse()

    fmt.Println("word:", *wordPtr)
    fmt.Println("numb:", *numbPtr)
    fmt.Println("fork:", *forkPtr)
    fmt.Println("svar:", svar)
    fmt.Println("tail:", flag.Args())
}
go run test_command_line.go --help

返回如下,基本可以满足常用命令行的构建

Usage of /tmp/go-build3476798509/b001/exe/test_command_line:
  -fork
    	a bool
  -numb int
    	an int (default 42)
  -svar string
    	a string var (default "bar")
  -word string
    	a string (default "foo")

当然也有很多第三方提供的Parser


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK