Skip to main content
In this article, we’ll explore how to read input from a user in Go using the fmt package. One common technique is to use the Scanf function, which requires a format string and a sequence of variables (passed with the address operator) where the input will be stored. The basic syntax is:
For example, if you want to read a string using the “%s” specifier, you would write:
The following sections provide examples on how to read various types of data and handle potential input errors.

Example 1: Reading a Single Input

In this example, we declare a variable to store the user’s name. The program prompts the user for input and then greets them.
When you run the program:
After entering a name (for instance, “Priyanka”), the output will be:

Example 2: Reading Multiple Inputs

You can capture multiple inputs in a single Scanf call by using multiple format specifiers and corresponding variables. In this example, the program asks for a user’s name and then whether they are a muggle.
If the user provides the input:
The output will be:
:::note Important Ensure that the order of the format specifiers in the format string exactly matches the order of the variables provided. :::

Example 3: Handling Input Errors

The fmt.Scanf function returns two values: the number of arguments successfully read and an error if one occurred. This is useful when you need to handle input errors. Consider the following example:
When you run the program:
If the user mistakenly enters two strings (for example, “Priyanka yes”), the function will successfully store the first argument but fail to convert the second input to an integer. The output might look like:
:::warning Input Mismatch Warning When the input doesn’t match the expected format, the function may not store values for some variables. For example, in the above code, the integer b remains its default zero value due to the incorrect input type. :::

Summary

This article demonstrated how to handle user input in Go using the fmt.Scanf function. We covered: In the next article, we will explore more advanced techniques and the role of pointers in reading user input in Go. For further reading, check out these resources: Happy coding!

Watch Video