package main import "fmt" import "os" import "strconv" func main() int{ arg_num := len(os.Args) fmt.Printf("the num of input is %d\n",arg_num) fmt.Printf("they are :\n") for i := 0 ; i < arg_num ;i++{ fmt.Println(os.Args[i]) } sum := 0 for i := 1 ; i < arg_num; i++{ curr,err := strconv.Atoi(os.Args[i]) if(err != nil){ fmt.Println("error happened ,exit") return 1 } sum += curr } fmt.Printf("sum of Args is %d\n",sum) return 0 }
输出
manu@manu-hacks:~/code/go/self$ ./sum 1 2 4 the num of input is 4 they are : ./sum 1 2 4 sum of Args is 7 manu@manu-hacks:~/code/go/self$ ./sum 1 2 4 f 5 the num of input is 6 they are : ./sum 1 2 4 f 5 error happened ,exit
获取系统环境变量
package main import "fmt" import "os" func main(){ environ := os.Environ() for i := range environ { fmt.Println(environ[i]) } fmt.Println("------------------------------------------------------------\n") logname := os.Getenv("LOGNAME") fmt.Printf("logname is %s\n",logname) }
输出
manu@manu-hacks:~/code/go/self$ go run env.go SSH_AGENT_PID=2331 GPG_AGENT_INFO=/tmp/keyring-5CkALe/gpg:0:1 TERM=xterm SHELL=/bin/bash 。。。 ------------------------------------------------------------ logname is manu
有疑问加站长微信联系(非本文作者)