In Go, you can read user input from the console using various methods depending on the type of input you expect. Here are a few examples:
- Reading a single line of text input:
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
reader := bufio.NewReader(os.Stdin)
fmt.Print("Enter your name: ")
name, _ := reader.ReadString('\n')
fmt.Printf("Hello, %s!\n", name)
}
- Reading an integer:
package main
import (
"fmt"
"os"
)
func main() {
var age int
fmt.Print("Enter your age: ")
_, err := fmt.Scanln(&age)
if err != nil {
fmt.Println("Invalid input for age.")
return
}
fmt.Printf("You are %d years old.\n", age)
}
- Reading a floating-point number:
package main
import (
"fmt"
"os"
)
func main() {
var weight float64
fmt.Print("Enter your weight (in kg): ")
_, err := fmt.Scanln(&weight)
if err != nil {
fmt.Println("Invalid input for weight.")
return
}
fmt.Printf("Your weight is %.2f kg.\n", weight)
}
- Reading multiple values on a single line:
package main
import (
"fmt"
"os"
)
func main() {
var name string
var age int
fmt.Print("Enter your name and age: ")
_, err := fmt.Scanln(&name, &age)
if err != nil {
fmt.Println("Invalid input.")
return
}
fmt.Printf("Hello, %s! You are %d years old.\n", name, age)
}
In each example, we prompt the user to enter specific information and then use different methods (bufio.NewReader()
with ReadString()
, fmt.Scanln()
, or fmt.Scan()
) to read the input from os.Stdin
(standard input).
Note that the error handling code (if err != nil
) is used to check for any input errors and handle them appropriately.
Feel free to modify these examples based on your specific input requirements.