User Input
This guide covers different methods of handling user input in Go programming language.
📝 Basic Input Methods
Using fmt.Scan
package main
import "fmt"
func main() {
var name string
fmt.Print("Enter your name: ")
fmt.Scan(&name)
fmt.Printf("Hello, %s!\n", name)
}Using fmt.Scanf
package main
import "fmt"
func main() {
var name string
var age int
fmt.Print("Enter name and age (e.g., John 25): ")
fmt.Scanf("%s %d", &name, &age)
fmt.Printf("Name: %s, Age: %d\n", name, age)
}Using fmt.Scanln
📖 Reading Strings
Using bufio.NewReader
Reading Multiple Lines
🔢 Reading Numbers
Integer Input
Float Input
🎯 Input Validation
Basic Validation
Advanced Validation
🔄 Interactive Input
Menu System
📝 File Input
Reading from File
💡 Best Practices
Error Handling
Always check for errors when reading input
Provide clear error messages to users
Handle invalid input gracefully
Input Buffering
Use
bufio.NewReaderfor reading strings with spacesClear input buffer after reading
Handle newline characters properly
Type Safety
Validate input before conversion
Use appropriate type conversion functions
Handle conversion errors
User Experience
Provide clear prompts
Give feedback for invalid input
Allow ways to exit or cancel
🔧 Common Issues and Solutions
Handling Newlines
Buffer Clearing
📚 Additional Resources
Last updated
Was this helpful?