How to take inputs from users in Go Language?

GoLang will feel similar to taking inputs in C, C++, and Java language. There are multiple ways to take input from a user in the Go language.

Let’s take a look at each one by one

Using Scanf() method

Scanf() function is part of the “fmt” package. It scans the input text given in the standard input, reads from there, and stores them in successive space-separated values into successive arguments as determined by the format. This is the same as we do in C or C++. We first define the variable type and then take input from the user using Scanf() function.

Code Example
package main

import (
	"fmt"
)

func main() {

	var age int

	fmt.Println("Enter your age: ")

	fmt.Scanf("%d", &age)

	fmt.Println("Age you entered is: ", age)
}

Output –

Enter your age: 
22
Age you entered is:  22

We have shown above how we can take an integer input, but what if we wanted to take the input of a float data type variable.

How to take input from users for a float data type variable using Scanf?

The format we will use here is %f for float-type variables.

package main

import (
	"fmt"
)

func main() {

	var height float32

	fmt.Println("Enter your height: ")

	fmt.Scanf("%f", &height) // we will enter our age here

	fmt.Println("height you entered is: ", height)
}

Output –

Enter your height: 
167.23
height you entered is:  167.23

Go language also supports a complex data type, so let’s see how to take input from the user for a complex data type.

How to take input from users for a complex data type variable using Scanf?

We can also use the %f format specifier for a complex data type. Below is the code sample for the same

package main

import (
	"fmt"
)

func main() {

	var comp complex64

	fmt.Println("Enter the complex no: ")

	fmt.Scanf("%f", &comp) // we will enter our age here

	fmt.Println("Compelex no: ", comp)
}

Output –

Enter the complex no: 
2+3i
Compelex no:  (2+3i)

Note: We can also use %g as a format specifier for float or complex data types.

Below is the table for what format specifier we can use for what data type. We have omitted many of the format specifiers and just written the most used ones.

Data TypeFormat specifier
bool%t
int, int8, int16, uint, uint8 etc.%d
float or complex data type%f or %g
string%s

How to take input for multiple variables in a single line using Scanf?

We can assign values to multiple variables in the same line by giving values separated by a space, and then they will be assigned to their respective variables. The variables may or may not be of the same type.

package main

import (
	"fmt"
)

func main() {

	var age int
	var height float32

	fmt.Println("Enter your age and height: ")

	fmt.Scanf("%d%f", &age, &height) // we will enter our age here

	fmt.Println("Age: ", age)
	fmt.Println("Height: ", height)
}

Output –

Enter your age and height: 
22 167.53
Age:  22
Height:  167.53
How to take input for multiple variables in multiple lines using Scanf?

If we want to take inputs in a new line for every variable. We have to use the newline character ( \n ) in between the format specifiers, as shown below.

package main

import (
	"fmt"
)

func main() {

	var age int
	var height float32

	fmt.Println("Enter your age and height: ")

	fmt.Scanf("%d\n%f", &age, &height) // we will enter our age here

	fmt.Println("Age: ", age)
	fmt.Println("Height: ", height)
}

Output –

Enter your age and height: 
12       
123.21
Age:  12
Height:  123.21

Using Scanln() method

Taking inputs using Scanln() feels like the same in C++, where we don’t have to write any format specifiers. The Golang will take care of it on its own. Please remember that Scanln will always take your cursor or line pointer to the next line after taking an input.

Code Example
package main

import (
	"fmt"
)

func main() {

	var age int

	fmt.Println("Enter your age: ")

	fmt.Scanln(&age)

	fmt.Println("Age you entered is: ", age)
}

Output –

Enter your age: 
20
Age you entered is:  20
Now, how to take input for multiple variables in a single line using Scanln?

To take input in a single line for multiple variables, we can pass the list of variables into the Scanln() function’s arguments and type the space-separated values for the respective variables.

package main

import (
	"fmt"
)

func main() {

	var age int
	var height float64
	var name string

	fmt.Println("Enter your age, height and name: ")

	fmt.Scanln(&age, &height, &name)

	fmt.Println("Age: ", age)
	fmt.Println("Height: ", height)
	fmt.Println("Name: ", name)
}

Output –

Enter your age, height and name: 
22 167.23 codekru
Age:  22
Height:  167.23
Name:  codekru
How to take input for multiple variables in multiple lines using Scanln?

For this to achieve, we will have to use as many Scanln methods as there are variables whose inputs we want to take from a user.

package main

import (
	"fmt"
)

func main() {

	var age int
	var height float64
	var name string

	fmt.Println("Enter your age: ")
	fmt.Scanln(&age)

	fmt.Println("Enter your height: ")
	fmt.Scanln(&height)

	fmt.Println("Enter your name: ")
	fmt.Scanln(&name)

	fmt.Println("===Output starts from here =====")

	fmt.Println("Age: ", age)
	fmt.Println("Height: ", height)
	fmt.Println("Name: ", name)
}

Output –

Enter your age: 
22
Enter your height: 
170.21
Enter your name: 
codekru
===Output starts from here =====
Age:  22
Height:  170.21
Name:  codekru

Using NewReader() method

NewReader and NewScanner will feel almost the same as what we did in Java with BufferReader and Scanner. It’s important to note that we said it is nearly the same because there are differences ( like In Go, functions can return multiple values ).

NewReader is a part of the bufio package, and it returns a new reader. It returns two output variables, one is the string itself, and the other is the error. In the below example, we will be using the ReadString() method to read a String from the input.

package main

import (
	"bufio"
	"fmt"
	"os"
)

func main() {

	bufferReader := bufio.NewReader(os.Stdin)

	fmt.Print("Enter your name: ")

	name, err := bufferReader.ReadString('\n')

	if err == nil {
		fmt.Println("Error did not happen")
	}

	fmt.Println("Hello, ", name)
}

Output –

Enter your name: codekru website
Error did not happen
Hello,  codekru website

So, what happened here?

  • First, we need to let the user know to enter something, so we used to fmt.Print to display a font. Here we have used Print instead of Println because Print doesn’t skip to a new terminal line after printing a message, which will help us retain the prompt and the user’s input in the same line.
  • Then, we need a way to receive and store the input from the program standard’s input ( anything that a user enters via keyboard). The line bufferReader := bufio.NewReader(os.Stdin) stores a bufio.Reader in the bufferReader variable which will store the user’s input for us.
  • And then, we used the ReadString() method to get the user’s input. The ReadString() method requires a rune ( character ) argument that marks the end of the input. As we wanted to read the input until the user pressed the Enter button, we gave a newline(‘\n’) rune into the function’s argument.
  • The ReadString () method returns two values: the actual string and the other is the error encountered while processing the string. There was no error in our case, so it returned nil.

Using NewScanner() method

NewScanner() is also a part of the bufio package.

package main

import (
	"bufio"
	"fmt"
	"os"
)

func main() {

	scanner := bufio.NewScanner(os.Stdin)
	fmt.Println("Enter your website name")
	scanner.Scan()

	fmt.Println("Output from scanning the input")
	fmt.Println(scanner.Text())
}

Output –

Enter your website name
Codekru
Output from scanning the input
Codekru

So, what happened here?

  • First, we read the input using the bufio.NewScanner(os.stdin) function by passing the standard input (os.stdin) into its argument.
  • Then Scanner.scan() scans the input and then scanner.Text() gives us the string typed in the standard input.
How to get multiline inputs using NewScanner()?

We can use a for loop with a condition to scan a new token every time, and when the token encounters a string of length 0, we will break from the for loop and thus finish our program.

package main

import (
	"bufio"
	"fmt"
	"os"
)

func main() {

	scanner := bufio.NewScanner(os.Stdin)
	for scanner.Scan() {
		str := scanner.Text()

		// len(str) will give the length of the string
		if len(str) == 0 {
			break // break from the for loop, when the length of the string is 0
		}

		fmt.Println("Input  entered is: ", str)
	}

}

Output –

Codekru
Input  entered is:  Codekru
Website
Input  entered is:  Website
Bye
Input  entered is:  Bye

Well, this is it. Hope you have liked the article. If you have any doubts or concerns, please feel free to write us in the comments or mail us at admin@codekru.com.

Related Articles
Liked the article? Share this on

Leave a Comment

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