In Go, you can read and write data from and to standard input/output using the bufio
package.
To read data from standard input (stdin), you can use the bufio.NewScanner()
function and scanner.Scan()
method to read line-by-line. Here's an example of reading input from the user:
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
scanner := bufio.NewScanner(os.Stdin)
fmt.Print("Enter your name: ")
scanner.Scan() // read input from user
name := scanner.Text()
fmt.Printf("Hello, %s!\n", name)
}
To write data to standard output (stdout), you can use the fmt
package. Here's an example of writing to stdout:
package main
import "fmt"
func main() {
name := "John Doe"
age := 30
// Writing to stdout
fmt.Println("Name:", name)
fmt.Println("Age:", age)
}
When you run the above code, it prompts the user to enter their name, then it reads the input from stdin and prints a greeting to stdout.