Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Apr 24th, 2012  |  syntax: None  |  size: 1.83 KB  |  hits: 16  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Global variables / Get command line argument and print it
  2. package main
  3.  
  4. import (
  5.     "flag"
  6.     "fmt"
  7. )
  8.  
  9. func main() {
  10.     gettext();
  11.     fmt.Println(text)
  12. }
  13.  
  14. func gettext() {
  15.     flag.Parse()
  16.     text := flag.Args()
  17.     if len(text) < 1 {
  18.         fmt.Println("Please give me some text!")
  19.     }
  20. }
  21.        
  22. package main
  23.  
  24. import (
  25.     "flag"
  26.     "fmt"
  27. )
  28.  
  29. func main() {
  30.     text := gettext()
  31.     fmt.Println(text)
  32. }
  33.  
  34. func gettext() []string {
  35.     flag.Parse()
  36.     text := flag.Args()
  37.     if len(text) < 1 {
  38.         fmt.Println("Please give me some text!")
  39.     }
  40.     return text
  41. }
  42.        
  43. var text string
  44.        
  45. package main
  46.  
  47. import (
  48.     "fmt"
  49.     "os"
  50. )
  51.  
  52. func main() {
  53.     if len(os.Args) < 2 {     // (program name is os.Arg[0])
  54.         fmt.Println("Please give me some text!")
  55.     } else {
  56.         fmt.Println(os.Args[1:])  // print all args
  57.     }
  58. }
  59.        
  60. package main
  61.  
  62. import (
  63.     "flag"
  64.     "fmt"
  65.     "os"
  66. )
  67.  
  68. //This is how you declare a global variable
  69. var someOption bool
  70.  
  71. //This is how you declare a global constant
  72. const usageMsg string = "goprog [-someoption] argsn"
  73.  
  74. func main() {
  75.     flag.BoolVar(&someOption, "someOption", false, "Run with someOption")
  76.     //Setting Usage will cause usage to be executed if options are provided
  77.     //that were never defined, e.g. "goprog -someOption -foo"
  78.     flag.Usage = usage
  79.     flag.Parse()
  80.     if someOption {
  81.         fmt.Printf("someOption was setn")
  82.     }
  83.     //If there are other required command line arguments, that are not
  84.     //options, they will now be available to parse manually.  flag does
  85.     //not do this part for you.
  86.     for _, v := range flag.Args() {
  87.         fmt.Printf("%+vn", v)
  88.     }
  89.  
  90.     //Calling this program as "./goprog -someOption dog cat goldfish"
  91.     //outputs
  92.     //someOption was set
  93.     //dog
  94.     //cat
  95.     //goldfish
  96. }
  97.  
  98. func usage() {
  99.     fmt.Printf(usageMsg)
  100.     flag.PrintDefaults()
  101.     os.Exit(1)
  102. }