user input iin go code example

Example 1: user input golang

import (
"fmt"
"bufio"
)

//reading an integer
var age int
fmt.Println("What is your age?") // Question to the user
_, err: fmt.Scan(&age)

//reading a string
reader := bufio.newReader(os.Stdin)
var name string
fmt.Println("What is your name?") // Question to the user
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')
    // convert CRLF to LF
    text = strings.Replace(text, "\n", "", -1)

    if strings.Compare("hi", text) == 0 {
      fmt.Println("hello, Yourself")
    }

  }

}

Tags:

Go Example