There are various occassions when we have to print values or variables to show to users. Similarly, there will be situations when we want to respond to user input in different ways. For this, we have to have a ability to take user input and flexibility to provide different output. This lesson teaches how to take user input and different ways to format string output.

Taking User Input

Before I show how to take user input, I would like to show how we can see the memory address for a variable.

1package main
2
3import "fmt"
4
5func main() {
6	name := "Bob"
7	fmt.Println(&name)
8}

Above code has a new operator &. We can access the memory address of the variable using this operator. So, when we execute this code, we get below result. This result will be different when you execute in your system. This is essentially the memory location where the name variable value is stored.

go run main.go
0xc000014080

This operator & is called address of operator. We can use this to assign values to a variable.

Scanf Function

In Golang, we can take user input from the terminal using Scanf function in fmt module. [Scanf function] takes format string along with variable number of arguments into which the input values will be stored. This function scans successive arguments from the stdin which are space separated and as specified by the format specifier. Interestingly, in Go, usually functions return multiple values. This is one such function where it returns two values: number of variables assigned and error if any during assignment.

 1package main
 2
 3import "fmt"
 4
 5func main() {
 6	var name string
 7	fmt.Print("Enter your name: ")
 8	fmt.Scanf("%s", &name)
 9	fmt.Println("Hello", name)
10}
go run main.go
Enter your name: Jay
Hello Jay

In this case, we specified that name variable should be of type string using format specifier %s. Also, when assigning values, we use & before the variable name. This will become clearer in the Pointers lesson in this tutorial. Let’s look at some of the most common format specifiers.

Format Specifiers

The format specifier are used to define what kind of data is to be printed or scanned. These are derived from C language.

Format SpecifierDescription
%vValue in default format. Works with most types.
%+vThis is useful for printing struct data type. This adds field names in output.
%TType of the value
%tBoolean value
%dBase 10 integer value
%sString
%ffloat
%.2fFloat with precision upto 2 digits
%eNumber in scientific notation, e.g. -1.234456e+78

For more information on format specifier refer to beginning of the fmt package.

Taking input for integer, boolean and float numbers.

 1package main
 2
 3import "fmt"
 4
 5func main() {
 6    var quantity int
 7    var price float32
 8    var isAvailable bool
 9    fmt.Scanf("%d %f %t", &quantity, &price, &isAvailable) // collecting three variables in single line
10    fmt.Println(quantity)
11    fmt.Println(price)
12    fmt.Println(isAvailable)
13}

In this example, we are taking three input variables in single line, each of them separated by space. When we hit new line, the values are assigned to each of those three variables in the format we have specified.

20 12.99 false
20
12.99
false

Let’s also verify the values returned by this Scanf function.

 1package main
 2
 3import "fmt"
 4
 5func main() {
 6    var str string
 7	var num int
 8	count, err := fmt.Scanf("%s %d", &str, &num)
 9	fmt.Println("Modified:", count)
10	fmt.Println("Error:", err)
11}

If we provide 2 input in the same pattern as the format specifier, that is string followed by space and that followed by integer. It gives this output.

go run main.go
Hello 2
Modified: 2
Error: <nil>

However, if we do not provide integer value which is specified in the format specifier, it throws an error as shown below.

go run main.go
Hello

In this case, it assigned only one variable str which is specified by Modified line and there is an error.

Modified: 1
Error: newline in input does not match format

Scanln Function

There is also Scanln function which stops scanning after new line. This function only takes values as string. So, if we take number as input, we will have to convert them to required data type.

 1package main
 2
 3import "fmt"
 4
 5func main() {
 6    var str string
 7	var num string
 8	count, err := fmt.Scanln(&str)
 9    count,err = fmt.Scanln(&num)
10    fmt.Println(str, num)
11}
go run main.go
Hello
There
Hello There

Printing and Formatting String

Again, fmt module contains string formatting functions. Let’s see few examples.

Println Function

Println function takes variable number of arguments and prints them separated by space. This also returns number of bytes written and error if any.

1name := "Angela"
2age := 20
3fmt.Println("My name is", name, "and I am", age, "years old.")
My name is Angela and I am 20 years old.

Printf Function

Similar to Scanf function, we also have Printf function which has C-style printing functionality using format specifier. The format specifiers mentioned above works for Printf function as well. This makes writing long string easier to read as those do not need to be separated by comma.

1name := "Angela"
2age := 20
3fmt.Printf("My name is %s and I am %d years old.\n", name, age)
My name is Angela and I am 20 years old.

Escape Sequences

Something interesting in this line is \n at the end of the line. This is called Escape Sequence in programming. Some of the characters starting with \ have special meaning. The character back slash (\) is used to escape next character and provide different meaning to next character as mentioned below.

  • \n - new line
  • \t - tab
  • \\ - prints single \
  • \" - escape double quote inside double quoted string

Conclusion

In this tutorial, we saw how to format string using various format specifiers. I showed two methods for taking user input from the console and two methods for printing string. We also briefly looked at escape sequences towards the end of this lesson.