User Input (bufio) in Go
In this post, you will learn how to work with the user input (bufio) so that you can use that same knowledge and thus evolve.
- the bufio library in conjunction with the function
NewReader()
and the functionReadString()
have as main objective “extract” information given by the user; - in short, this same junction serves to increase interaction with it;
package main
import (
"fmt"
"bufio"
"os"
"strings"
)
func main() {
userInput := bufio.NewReader(os.Stdin)
fmt.Print("Enter your first name: ")
firstName, _ := userInput.ReadString('\n')
fmt.Print("Enter your last name: ")
lastName, _ := userInput.ReadString('\n')
fmt.Print("Enter your age: ")
age, _ := userInput.ReadString('\n')
/*
CR+LF -> \r\n
CR -> \r
LF -> \n
*/
fmt.Printf("Name: %s %s\nAge: %s",
strings.ReplaceAll(firstName, "\r\n", ""),
strings.ReplaceAll(lastName, "\r\n", ""),
strings.ReplaceAll(age, "\r\n", ""))
Don’t forget to watch the video and you can always read this post in Portuguese.