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.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.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: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!