Basic Input Output

The basics of accepting data from stdin, and displaying data to stdout

Standard Out - Displaying Info

Golang uses very similar syntax to C and other well known programming languages

std_io.go
package main

import "fmt"

func main() {
    fmt.Println("hello there")
    fmt.Println("7 + 10 = ", 7+10) // prints "7 + 10 = 17"
    fmt.Printf("Planck Constant: %f\n", 6.62607e-34) // prints Planck Constant: 0.000000
    fmt.Println(true && false) // prints false
    fmt.Println(true || false) // prints true
    fmt.Println(!true && (false || true) || true) // prints true
}

Go provides various ways of printing values to the stdout. These include:

fmt.Println(arg) // prints arg to stdout with a new line at the end
fmt.Println(arg_1, arg_2, ... arg_n) // prints all arguments on one line
fmt.Printf("%<formatter>", arg) // prints arg using C-style string formatting
fmt.Sprint(arg) // Sprint formats using the default formats for its operands

Standard In - Accepting User Input

User input is very similar to C-style user input

user_input.go
package main

import "fmt"

// main function
func main() {
    fmt.Println("Who painted 'The Starry Night'?: ")
    var painter_name string

    // Taking input from user
    fmt.Scanln(&painter_name)
    fmt.Println("What year was it painted?: ")
    var year_painted int
    fmt.Scan(&year_painted)

    // Print the output
    fmt.Println("\n==========================")
    fmt.Printf("Painted by %s\n", painter_name)
    fmt.Printf("In the year %d\n", year_painted)
}
$ go run user_input.go
Who painted 'The Starry Night'?: 
Vincent
What year was it painted?: 
1889
==========================
Painted by Vincent
In the year 1889

Golang fmt package automatically splits input on spaces, so in the example above, entering "Vincent van Gogh" in the painter name prompt will not work. To accept input with spaces, we can do the following

import(
  "bufio"
  "os"
  "fmt"
  )
func main(){
  in := bufio.NewReader(os.Stdin)
  line, err := in.ReadString('\n')
  fmt.Println(line)
}

Last updated