How to Scan in GoLang
In Go (golang), the fmt package provides several functions for scanning input from the console or other input sources.
For me these have always been useful during test and so many other areas. And so far I usually work with 4 functions during scanning.
Let's explore some of them and see how, why and when to use it.
1. fmt.Scan
- Purpose: Reads space-separated input from standard input (console).
- Stops Reading: Stops on the first newline or whitespace.
- Multiple Variables: Can read multiple variables in one call.
- Returns: Number of successfully scanned items and error if any.
Example:
package main import ( "fmt" ) func main() { var name string var age int fmt.Print("Enter your name and age: ") fmt.Scan(&name, &age) // Reading input separated by space fmt.Printf("Hello %s, you are %d years old.\n", name, age) }
Input Example:
Alice 25
Output:
Hello Alice, you are 25 years old.
2. fmt.Scanln
- Purpose: Reads input until a newline (n) is encountered.
- Stops Reading: Stops on newline instead of whitespace.
- Multiple Variables: Can read multiple variables but stops if it reaches newline first.
- Returns: Number of successfully scanned items and error if any.
Example:
package main import ( "fmt" ) func main() { var name string var age int fmt.Print("Enter your name and age: ") fmt.Scanln(&name, &age) // Reads until newline is encountered fmt.Printf("Hello %s, you are %d years old.\n", name, age) }
Input Example:
Alice 25
Output:
Hello Alice, you are 25 years old.
3. fmt.Scanf
- Purpose: Reads formatted input using format specifiers (like %s, %d, %f).
- Stops Reading: Stops based on the specified format.
- Multiple Variables: Can read multiple variables with precise control using format specifiers.
- Returns: Number of successfully scanned items and error if any.
Example:
package main import ( "fmt" ) func main() { var name string var age int fmt.Print("Enter your name and age (formatted): ") fmt.Scanf("%s %d", &name, &age) // Reads formatted input fmt.Printf("Hello %s, you are %d years old.\n", name, age) }
Input Example:
Alice 25
Output:
Hello Alice, you are 25 years old.
4. bufio.NewReader (For Advanced Input Handling)
- Purpose: Provides more advanced input reading capabilities compared to fmt.
- Stops Reading: Allows reading an entire line including spaces.
- Multiple Variables: Reads input as a single string and then can be split further if needed.
- Returns: The complete input line as a string.
Example:
package main import ( "bufio" "fmt" "os" "strings" ) func main() { reader := bufio.NewReader(os.Stdin) fmt.Print("Enter your name and age: ") input, _ := reader.ReadString('\n') // Reads entire line including spaces input = strings.TrimSpace(input) // Trim newline and spaces fmt.Printf("You entered: %s\n", input) }
Input Example:
Alice 25
Output:
package main import ( "fmt" ) func main() { var name string var age int fmt.Print("Enter your name and age: ") fmt.Scan(&name, &age) // Reading input separated by space fmt.Printf("Hello %s, you are %d years old.\n", name, age) }
? Summary Table:
|
Purpose | Stops Reading At | Supports Formatting? | Multiple Variables? | Use Case | ||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
fmt.Scan | Basic scanning | Whitespace | ❌ | ✅ | Simple input without newline | ||||||||||||||||||||||||||||||
fmt.Scanln | Scans until newline | Newline (n) | ❌ | ✅ | Input until newline | ||||||||||||||||||||||||||||||
fmt.Scanf | Formatted input scanning | Controlled by format | ✅ | ✅ | Precise formatted input | ||||||||||||||||||||||||||||||
bufio.NewReader | Advanced input handling | Customizable | ✅ | ❌ | Large input with spaces |
The above is the detailed content of How to Scan in GoLang. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

OpenSSL, as an open source library widely used in secure communications, provides encryption algorithms, keys and certificate management functions. However, there are some known security vulnerabilities in its historical version, some of which are extremely harmful. This article will focus on common vulnerabilities and response measures for OpenSSL in Debian systems. DebianOpenSSL known vulnerabilities: OpenSSL has experienced several serious vulnerabilities, such as: Heart Bleeding Vulnerability (CVE-2014-0160): This vulnerability affects OpenSSL 1.0.1 to 1.0.1f and 1.0.2 to 1.0.2 beta versions. An attacker can use this vulnerability to unauthorized read sensitive information on the server, including encryption keys, etc.

Backend learning path: The exploration journey from front-end to back-end As a back-end beginner who transforms from front-end development, you already have the foundation of nodejs,...

Queue threading problem in Go crawler Colly explores the problem of using the Colly crawler library in Go language, developers often encounter problems with threads and request queues. �...

The library used for floating-point number operation in Go language introduces how to ensure the accuracy is...

Under the BeegoORM framework, how to specify the database associated with the model? Many Beego projects require multiple databases to be operated simultaneously. When using Beego...

The difference between string printing in Go language: The difference in the effect of using Println and string() functions is in Go...

The problem of using RedisStream to implement message queues in Go language is using Go language and Redis...

What should I do if the custom structure labels in GoLand are not displayed? When using GoLand for Go language development, many developers will encounter custom structure tags...
