Home >Backend Development >Golang >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.
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.
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.
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.
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) }
|
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!