GO Command Line Arguments

  • Command line arguments allow us to enter variables directly when starting a program. We show how this is done in the GO language.
  • program3.go shows how this is done.
/* program3.go */

package main
import ( "fmt"; "os"; "strconv" )

func main() {
   if len(os.Args) != 3 {
      fmt.Println("Two arguments expected")
      return
   }
   m, _ := strconv.Atoi(os.Args[1])
   n, _ := strconv.Atoi(os.Args[2])

   for i:=0; i<m; i++ {
      for j:=0; j<n; j++ {
         fmt.Printf("%3d", i+j)
      }
      fmt.Printf("\n");
   }
}
  • The program is run as follows:
    • go run program3.go 2 5
  • Alternatively you can build the executable file first:
    • go build program3.go
  • and then run it as follows (in bash):
    • ./program3 2 5
  • or in Windows cmd or command:
    • program3 2 5