To read a value from stdin into a variable and output its value in Go, you can use the fmt.Scan
function. Here's an example:
main.go231 chars15 lines
In the above code, we define a variable v
of type int
to store the user input. We then prompt the user to enter a number using the fmt.Println
function. The fmt.Scan
function is then used to read the input from stdin into the variable v
. The fmt.Scan
function returns two values: the number of items successfully scanned and any error that occurred. We ignore the first value using the blank identifier (_
) and handle the error if it occurs. Finally, we print the value of v
using the fmt.Println
function.
Note that the fmt.Scan
function can be used to read values of different types by providing a pointer to the variable you want to store the input in. In this example, we used &v
to pass a pointer to the v
variable.
You can run this code and test it by providing an input number when prompted and observing the output.
gistlibby LogSnag