Go fmt.Scan, Scanln, Scanf: Reading User Input

beginner
18 min

Go fmt.Scan, Scanln, Scanf: Reading User Input

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! šŸ’¦

Why Read User Input? šŸ“

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.

fmt.Scan: Reading Input from Standard Input šŸŽÆ

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.

go
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.

Scanln: Reading a Single Line of Input šŸ“

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.

go
package main import ( "fmt" ) func main() { var input string fmt.Print("Enter something: ") fmt.Scanln(&input) fmt.Printf("You entered: %s\n", input) }

Scanf: Formatted Input Reading šŸŽÆ

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.

go
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).

Practice Time šŸŽÆ

Now that you've learned the basics, let's put your knowledge into practice!

Quick Quiz
Question 1 of 1

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! šŸŽÆ