Rumah >pembangunan bahagian belakang >Golang >Cara Mengimbas dalam GoLang
Dalam Go (golang), pakej fmt menyediakan beberapa fungsi untuk mengimbas input daripada konsol atau sumber input lain.
Bagi saya ini sentiasa berguna semasa ujian dan banyak lagi bidang lain. Dan setakat ini saya biasanya bekerja dengan 4 fungsi semasa pengimbasan.
Mari kita terokai sebahagian daripadanya dan lihat cara, sebab dan bila untuk menggunakannya.
Contoh:
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) }
Contoh Input:
Alice 25
Output:
Hello Alice, you are 25 years old.
Contoh:
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) }
Contoh Input:
Alice 25
Output:
Hello Alice, you are 25 years old.
Contoh:
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) }
Contoh Input:
Alice 25
Output:
Hello Alice, you are 25 years old.
Contoh:
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) }
Contoh Input:
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) }
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 |
Atas ialah kandungan terperinci Cara Mengimbas dalam GoLang. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!