To read user input from the command line in Go, you can use the bufio
package along with os.Stdin
to create a new Scanner
object. Then, you can use the Scan()
method to read input from the user.
Here's an example of how you can read user input from the command line in Go:
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
fmt.Print("Enter your name: ")
scanner := bufio.NewScanner(os.Stdin)
scanner.Scan()
name := scanner.Text()
fmt.Println("Hello, " + name + "!")
}
In this example, the fmt.Print
function is used to display a prompt to the user. Then, we create a new Scanner
object called scanner
using bufio.NewScanner(os.Stdin)
. os.Stdin
represents the standard input, which is the command line.
Next, we call the Scan()
method on the scanner
object to read the user's input. The scanner.Text()
method retrieves the text that was scanned. We store the user's input in the name
variable.
Finally, we display a welcome message to the user using the fmt.Println
function.
When you run this program, it will prompt you to enter your name in the command line.