In this page, I put together some random Go Scripts that I use to learn the language.


Go - Hello World
              
package main

import "fmt"

func main() {
  fmt.Println("Hello World\n")
}
              
              
Go - Read file
              
package main

import(
  "fmt"
  "bufio"
  "io/ioutil"
  "os"
)

func main() {
    // Read Text File by Lines
    f, _ := os.Open("sample.txt")
    scanner := bufio.NewScanner(f)
    for scanner.Scan() {
      fmt.Println(scanner.Text()) // Println will add back the final '\n'
    }
    f.Close()

    // Read Text File by Words
    f, _ = os.Open("sample.txt")
    scanner = bufio.NewScanner(f)
    scanner.Split(bufio.ScanWords)
    for scanner.Scan() {
      fmt.Println(scanner.Text()) // Println will add back the final '\n'
    }
    f.Close()

    // Read Whole Text file
    dat, _ := ioutil.ReadFile("sample.txt")
    fmt.Println(string(dat))
}
              
              
Go - Read lines from Standard Input
              
reader := bufio.NewReader(os.Stdin)

for {
  text, err := reader.ReadString('\n')
  if (err == io.EOF) { os.Exit(0) }
}
              
              
Go - Read numbers split by commas
              
package main

import(
  "fmt"
  "bufio"
  "os"
  "strconv"
  "io"
)

func main() {
  // Read Text File by Lines
  f, _ := os.Open("numbers.txt")
  reader := bufio.NewReader(f)

  var sum, num int64

  for {
    text, err := reader.ReadString(',')
    text = text[0:len(text) - 1]
    if (err == io.EOF) { break }
    num, _ = strconv.ParseInt(text, 10, 64)
    fmt.Println(text)
    sum += num
  }

  fmt.Println(sum)
}