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

📝 File Input

Reading from File

💡 Best Practices

  1. Error Handling

    • Always check for errors when reading input

    • Provide clear error messages to users

    • Handle invalid input gracefully

  2. Input Buffering

    • Use bufio.NewReader for reading strings with spaces

    • Clear input buffer after reading

    • Handle newline characters properly

  3. Type Safety

    • Validate input before conversion

    • Use appropriate type conversion functions

    • Handle conversion errors

  4. 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?