Basic I O
Context
Section titled “Context”Go provides several ways to read input and write output. The most common are:
- Output:
fmt.Print,fmt.Println,fmt.Printf - Input:
fmt.Scan,fmt.Scanln,fmt.Scanf, andbufiofor full lines.
Example
Section titled “Example”Read a name and age from the user, then print a greeting.
Code example
Section titled “Code example”package main
import ( "bufio" "fmt" "os" "strconv" "strings")
func main() { reader := bufio.NewReader(os.Stdin)
fmt.Print("Enter your name: ") name, _ := reader.ReadString('\n') name = strings.TrimSpace(name)
fmt.Print("Enter your age: ") ageStr, _ := reader.ReadString('\n') age, _ := strconv.Atoi(strings.TrimSpace(ageStr))
fmt.Printf("Hello %s, you are %d years old.\n", name, age)}Example interaction
Section titled “Example interaction”Enter your name: AliceEnter your age: 30Hello Alice, you are 30 years old.