How to Take Input in Go: Simple Guide with Examples
In Go, you can take input from the user using
fmt.Scan, fmt.Scanln, or bufio.Reader. The fmt.Scan functions read input from the standard input (keyboard) and store it in variables.Syntax
To take input in Go, you commonly use the fmt.Scan or fmt.Scanln functions. They read input from the keyboard and store it in variables passed by reference.
fmt.Scan(&variable): Reads input separated by spaces.fmt.Scanln(&variable): Reads input until a newline.bufio.NewReader(os.Stdin): For reading full lines or more complex input.
go
var name string fmt.Scan(&name) // reads a word var age int fmt.Scanln(&age) // reads an integer until newline reader := bufio.NewReader(os.Stdin) line, _ := reader.ReadString('\n') // reads a full line including spaces
Example
This example shows how to take a user's name and age as input and then print a greeting message.
go
package main import ( "bufio" "fmt" "os" "strings" ) func main() { var name string var age int fmt.Print("Enter your name: ") fmt.Scanln(&name) fmt.Print("Enter your age: ") fmt.Scan(&age) reader := bufio.NewReader(os.Stdin) fmt.Print("Enter your favorite quote: ") quote, _ := reader.ReadString('\n') quote = strings.TrimSpace(quote) fmt.Printf("Hello %s, you are %d years old.\n", name, age) fmt.Printf("Your favorite quote is: %s\n", quote) }
Output
Enter your name: Alice
Enter your age: 30
Enter your favorite quote: Go is awesome!
Hello Alice, you are 30 years old.
Your favorite quote is: Go is awesome!
Common Pitfalls
Common mistakes when taking input in Go include:
- Not using the address operator
&when passing variables tofmt.Scanorfmt.Scanln. - Mixing
fmt.Scanandbufio.Readerwithout clearing the input buffer, which can cause unexpected behavior. - Assuming
fmt.Scanreads the whole line; it stops at spaces.
Always handle errors returned by input functions for robust code.
go
package main import ( "fmt" ) func main() { var name string // Wrong: missing & operator // fmt.Scanln(name) // This will cause a compile error // Right: fmt.Scanln(&name) fmt.Printf("Hello %s\n", name) }
Quick Reference
Here is a quick summary of input functions in Go:
| Function | Description | Notes |
|---|---|---|
| fmt.Scan(&vars) | Reads space-separated values from stdin | Stops at space, requires & |
| fmt.Scanln(&vars) | Reads input until newline | Stops at newline, requires & |
| bufio.Reader.ReadString('\n') | Reads full line including spaces | Returns string with newline, trim if needed |
| bufio.Reader.ReadBytes('\n') | Reads bytes until newline | Useful for binary or raw input |
Key Takeaways
Use fmt.Scan or fmt.Scanln with &variable to read input from the keyboard.
bufio.Reader is useful for reading full lines or complex input with spaces.
Always pass variables by reference using & when scanning input.
Handle input errors and be aware of how input functions treat spaces and newlines.
Mixing fmt.Scan and bufio.Reader requires care to avoid leftover input issues.