Golang getting command-line arguments and environment variables

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.
package mainimport  "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}

Output

manu@manu-hacks:~/code/go/self$./sum 1 2 4 The num of input is 4they be:./sum124sum of Args is 7manu@manu-hacks:~/code/ go/self$./sum 1 2 4 F 5 The num of input is 6they be:./sum124f5error happened, exit


Get System Environment variables

Package Mainimport "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)}

Output

manu@manu-hacks:~/code/go/self$ Go run env.go ssh_agent_pid=2331gpg_agent_info=/tmp/keyring-5ckale/gpg:0:1term= Xtermshell=/bin/bash ... ------------------------------------------------------------LogName is Manu


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.