golang user input code example
Example 1: user input golang
import (
"fmt"
"bufio"
)
var age int
fmt.Println("What is your age?")
_, err: fmt.Scan(&age)
reader := bufio.newReader(os.Stdin)
var name string
fmt.Println("What is your name?")
name, _ := reader.readString('\n')
fmt.Println("Your name is ", name, " and you are age ", age)
}
Example 2: golang get terminal input
package main
import (
"bufio"
"fmt"
"os"
"strings"
)
func main() {
reader := bufio.NewReader(os.Stdin)
fmt.Println("Simple Shell")
fmt.Println("---------------------")
for {
fmt.Print("-> ")
text, _ := reader.ReadString('\n')
text = strings.Replace(text, "\n", "", -1)
if strings.Compare("hi", text) == 0 {
fmt.Println("hello, Yourself")
}
}
}
Example 3: How to read an input in golang
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
names := make([]string, 0)
scanner := bufio.NewScanner(os.Stdin)
for {
fmt.Print("Enter name: ")
scanner.Scan()
text := scanner.Text()
if len(text) != 0 {
fmt.Println(text)
names = append(names, text)
} else {
break
}
}
fmt.Println(names)
}