Here are some notes to explain it. First, mostly all you need is to understand the bufio
package. The documentation for that is here:
https://golang.org/pkg/bufio/
In my example,
stdin = bufio.NewReader(os.Stdin)
gets a handle (called a “Reader
”) for buffered reading from the standard input (console input) using other methods in bufio
.
c, _, err = stdin.ReadRune()
This reads a rune from the standard input.ReadRune()
returns 3 values: the rune, the number of bytes it takes up, and an error type. I use the blank identifier (_
) for the second return value because I don’t use it for anything. (If you don’t need to support Unicode and use ReadByte()
instead, then there are only two return values, and the blank identifier would not be needed.)
After ReadRune()
returns, c
contains the rune that was read, and err
can be checked to see if an error happened, or if the end of the file was encountered.
if err == io.EOF || c == '\n' { break }
Next, I check to see if it has encountered the end of file (in which case err
will be set to io.EOF
), or made it to the end of the line (and has read a newline, \n
). In the four lines after that, I catch any other error condition that ReadRune()
may have encountered.
line = append(line,c)
If things went ok reading the character, I append it toline[]
, which is a slice of runes. (append()
is one of Go’s built-in functions.)
Otherwise, the loop terminates, and I print the result. Notice that I don’t save the newline in the slice, so I have to add a newline with the Printf()
call. The %s
verb in the literal string given to Printf()
expects a string
type, so
string(line[:len(line)])
is in there to convert the slice of runes into a string
.