Introduction
We use input to let the user give information to the program. This helps the program do different things based on what the user wants.
package main import ( "bufio" "fmt" "os" ) func main() { reader := bufio.NewReader(os.Stdin) input, _ := reader.ReadString('\n') fmt.Println("You typed:", input) }
bufio.NewReader(os.Stdin) to read input from the keyboard.ReadString('\n') method reads until the user presses Enter.fmt.Scanln to read a single word input from the user.package main import ( "fmt" ) func main() { var name string fmt.Print("Enter your name: ") fmt.Scanln(&name) fmt.Println("Hello,", name) }
bufio.NewReader.package main import ( "bufio" "fmt" "os" ) func main() { reader := bufio.NewReader(os.Stdin) fmt.Print("Enter a sentence: ") text, _ := reader.ReadString('\n') fmt.Println("You wrote:", text) }
package main import ( "bufio" "fmt" "os" "strings" ) func main() { reader := bufio.NewReader(os.Stdin) fmt.Print("What is your favorite color? ") color, _ := reader.ReadString('\n') color = strings.TrimSpace(color) // remove newline fmt.Printf("Wow! %s is a nice color.\n", color) }
fmt.Scanln for simple inputs without spaces, and bufio.NewReader for full lines._ but in real programs handle errors properly.fmt.Scanln for simple word inputs and bufio.NewReader for full lines.var name string
fmt.Print("Enter name: ")
fmt.Scanln(&name)
fmt.Println("Hello,", name)
If the user types: John and presses Enter.var input string
reader := bufio.NewReader(os.Stdin)
input, _ = reader.ReadString('\n')
fmt.Println(input)Pass the test and this pattern moves unknown