Skip to content

Read User Input From Terminal (Stdin) In Golang

Ok, we want to accept input from the user for example from the command line (terminal). Our friend, the fmt package is with us! Scanln method from fmt package can read from standard input and put it in our variable:

fmt.Scanln(&userName)

// Scanln() stops scanning at a newline and after the final item there must be a newline or EOF.

Just remember to pass the address of variable (with &), see this simple working example:

package main

import (
	"fmt"
)

func main() {
	var userName string

	fmt.Println("Enter your name:")

	fmt.Scanln(&userName)

	fmt.Println("Your name is", userName)
}

Leave a Reply

Your email address will not be published. Required fields are marked *