Welcome to our comprehensive guide on Go's fmt.Scan, Scanln, and Scanf functions! In this lesson, we'll explore these powerful tools for reading user input in Go programs. Let's dive in! š¦
In many applications, reading user input is essential for creating interactive and user-friendly programs. Go provides various functions for handling user input, and fmt.Scan, Scanln, and Scanf are some of the most commonly used ones.
The fmt.Scan function is used to read user input from the standard input (keyboard). It can read multiple values of different types in a single call, making it an efficient choice for handling user input.
package main
import (
"fmt"
)
func main() {
var name, age string
fmt.Print("Enter your name: ")
fmt.Scan(&name)
fmt.Print("Enter your age: ")
fmt.Scan(&age)
fmt.Printf("Hello, %s! You are %s years old.\n", name, age)
}š Note: fmt.Scan reads input up to the first whitespace character by default. To read a line, use bufio package instead.
Go's Scanln function reads a single line of input from the standard input (keyboard) and stores it in a string variable. It is useful when you want to read a complete line of input without worrying about whitespace characters.
package main
import (
"fmt"
)
func main() {
var input string
fmt.Print("Enter something: ")
fmt.Scanln(&input)
fmt.Printf("You entered: %s\n", input)
}The Scanf function is used to read user input using format specifiers, similar to printf and fmt.Println functions. It can read different types of input and store them in the appropriate variables.
package main
import (
"fmt"
)
func main() {
var name string
var age int
fmt.Print("Enter your name: ")
fmt.Scanf("%s\n", &name)
fmt.Print("Enter your age: ")
fmt.Scanf("%d\n", &age)
fmt.Printf("Hello, %s! You are %d years old.\n", name, age)
}š Note: Scanf skips leading whitespace characters by default. If you want to read spaces as part of the input, use the space character as a format specifier (%s for strings and %d for integers).
Now that you've learned the basics, let's put your knowledge into practice!
Given the following code, what will be the output?
That's all for now! In the next lesson, we'll explore Go's error handling and how to deal with user input errors gracefully. Until then, happy coding! šÆ