Home Backend Development Golang How to Scan in GoLang

How to Scan in GoLang

Jan 05, 2025 pm 02:51 PM

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)
}
Copy after login
Copy after login

Input Example:

Alice 25

Output:

Hello Alice, you are 25 years old.
Copy after login
Copy after login
Copy after login

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)
}
Copy after login

Input Example:

Alice 25

Output:

Hello Alice, you are 25 years old.
Copy after login
Copy after login
Copy after login

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)
}
Copy after login

Input Example:

Alice 25

Output:

Hello Alice, you are 25 years old.
Copy after login
Copy after login
Copy after login

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)
}
Copy after login

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)
}
Copy after login
Copy after login

? Summary Table:

Function 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
Function
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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What are the vulnerabilities of Debian OpenSSL What are the vulnerabilities of Debian OpenSSL Apr 02, 2025 am 07:30 AM

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.

Transforming from front-end to back-end development, is it more promising to learn Java or Golang? Transforming from front-end to back-end development, is it more promising to learn Java or Golang? Apr 02, 2025 am 09:12 AM

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

How to specify the database associated with the model in Beego ORM? How to specify the database associated with the model in Beego ORM? Apr 02, 2025 pm 03:54 PM

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

What is the problem with Queue thread in Go's crawler Colly? What is the problem with Queue thread in Go's crawler Colly? Apr 02, 2025 pm 02:09 PM

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

What libraries are used for floating point number operations in Go? What libraries are used for floating point number operations in Go? Apr 02, 2025 pm 02:06 PM

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

How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? Apr 02, 2025 pm 04:54 PM

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

In Go, why does printing strings with Println and string() functions have different effects? In Go, why does printing strings with Println and string() functions have different effects? Apr 02, 2025 pm 02:03 PM

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

What should I do if the custom structure labels in GoLand are not displayed? What should I do if the custom structure labels in GoLand are not displayed? Apr 02, 2025 pm 05:09 PM

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

See all articles