Last Updated: February 25, 2016
·
655
· dradtke

Read a full line of input in Go

Go's fmt package has a strict "space-delimited" requirement when reading input. In order to read a full line, you'll need to use a method like this:

package main

import (
    "bufio"
    "fmt"
    "os"
)

// read *all* input up to the newline
func readln(r *bufio.Reader) (string, error) {
    var (
        isPrefix bool = true
        err error     = nil
        line, ln []byte
    )

    for isPrefix && err == nil {
        line, isPrefix, err = r.ReadLine()
        ln = append(ln, line...)
    }

    return string(ln), err
}

func main() {
    in := bufio.NewReader(os.Stdin)
    var name string

    fmt.Print("Enter your name: ")
    name,_ = readln(in)
    fmt.Printf("Welcome, %s.\n", name)
}