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!

Go uses the "encoding/binary" package for binary encoding and decoding. 1) This package provides binary.Write and binary.Read functions for writing and reading data. 2) Pay attention to choosing the correct endian (such as BigEndian or LittleEndian). 3) Data alignment and error handling are also key to ensure the correctness and performance of the data.

The"bytes"packageinGooffersefficientfunctionsformanipulatingbyteslices.1)Usebytes.Joinforconcatenatingslices,2)bytes.Bufferforincrementalwriting,3)bytes.Indexorbytes.IndexByteforsearching,4)bytes.Readerforreadinginchunks,and5)bytes.SplitNor

Theencoding/binarypackageinGoiseffectiveforoptimizingbinaryoperationsduetoitssupportforendiannessandefficientdatahandling.Toenhanceperformance:1)Usebinary.NativeEndianfornativeendiannesstoavoidbyteswapping.2)BatchReadandWriteoperationstoreduceI/Oover

Go's bytes package is mainly used to efficiently process byte slices. 1) Using bytes.Buffer can efficiently perform string splicing to avoid unnecessary memory allocation. 2) The bytes.Equal function is used to quickly compare byte slices. 3) The bytes.Index, bytes.Split and bytes.ReplaceAll functions can be used to search and manipulate byte slices, but performance issues need to be paid attention to.

The byte package provides a variety of functions to efficiently process byte slices. 1) Use bytes.Contains to check the byte sequence. 2) Use bytes.Split to split byte slices. 3) Replace the byte sequence bytes.Replace. 4) Use bytes.Join to connect multiple byte slices. 5) Use bytes.Buffer to build data. 6) Combined bytes.Map for error processing and data verification.

Go's encoding/binary package is a tool for processing binary data. 1) It supports small-endian and large-endian endian byte order and can be used in network protocols and file formats. 2) The encoding and decoding of complex structures can be handled through Read and Write functions. 3) Pay attention to the consistency of byte order and data type when using it, especially when data is transmitted between different systems. This package is suitable for efficient processing of binary data, but requires careful management of byte slices and lengths.

The"bytes"packageinGoisessentialbecauseitoffersefficientoperationsonbyteslices,crucialforbinarydatahandling,textprocessing,andnetworkcommunications.Byteslicesaremutable,allowingforperformance-enhancingin-placemodifications,makingthispackage

Go'sstringspackageincludesessentialfunctionslikeContains,TrimSpace,Split,andReplaceAll.1)Containsefficientlychecksforsubstrings.2)TrimSpaceremoveswhitespacetoensuredataintegrity.3)SplitparsesstructuredtextlikeCSV.4)ReplaceAlltransformstextaccordingto


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

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

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

Dreamweaver Mac version
Visual web development tools

Dreamweaver CS6
Visual web development tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.
