在Go(golang)中,fmt包提供了几个用于扫描来自控制台或其他输入源的输入的函数。
对我来说,这些在测试和许多其他领域一直很有用。到目前为止,我在扫描时通常使用 4 个功能。
让我们探索其中的一些,看看如何、为什么以及何时使用它。
示例:
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) }
输入示例:
爱丽丝 25
输出:
Hello Alice, you are 25 years old.
示例:
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) }
输入示例:
爱丽丝 25
输出:
Hello Alice, you are 25 years old.
示例:
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) }
输入示例:
爱丽丝 25
输出:
Hello Alice, you are 25 years old.
示例:
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) }
输入示例:
爱丽丝 25
输出:
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) }
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 |
以上是如何用 Go 语言进行扫描的详细内容。更多信息请关注PHP中文网其他相关文章!