I am trying to capture user input in Go with little luck. I can get non-spaced words to work:
var s string
println("enter string:")
fmt.Scan(&s)
However, the Go documentation says that scan will delimit at spaces and new lines. So I think I have to set up bufio.Reader's ReadLine. Here is my attempt, which will not compile:
package main
import (
"bufio"
"os"
"fmt"
)
const delim = '\n'
const file = "file"
func main() {
r := bufio.NewReader() *Reade开发者_StackOverflow社区r
println("enter string:")
line, err := r.ReadString(delim)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
fmt.Println(line)
}
errors:
1.go:14: not enough arguments in call to bufio.NewReader
1.go:14: undefined: Reader
So, how do I define "Reader"? And if it was defined, would this be the correct way to capture the input as a string, delimited at "\n", and not at the space? Or should I be doing something completely different?
Thanks in advance.
Change
r := bufio.NewReader() *Reader
to read
r := bufio.NewReader(os.Stdin)
to fix the problem.
The original encantation is incorrect because you seem to just copied and pasted the method's signature from the spec, but the spec defines the signature, not an example of a call, so *Reader
in there is the method's return type (the type your variable r
will have). And the method's sole argument is defined to be rd io.Reader
; that interface is conveniently implemented by the os.Stdin
symbol which seems like a perfect match for your task.
P.S. Consider reading all the docs in the "Learning Go" documentation section, especially "Effective Go".
If you look at the documentation for bufio.NewReader
, it takes an argument of type io.Reader
(which makes sense, because it takes a normal reader and makes it buffered, similar to java.io.BufferedReader
in Java, which also takes a Reader
argument). What is io.Reader
? Looking at its documentation, it is an interface, specifying anything that has a Read
method. Many types have a Read
method; most commonly, *os.File
. So you can construct a File
using os.Open
etc.
f, _ := os.Open(file)
r := bufio.NewReader(f)
精彩评论