在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中文網其他相關文章!