We often face the need to display something on the screen or receive an input text from users or another program. In programming, these operations are called input and output operations or, simply, I/O.
In this topic, we'll learn how to perform basic IO operations in Go. We use the fmt package from the standard library since it's a useful tool for working with I/O.
The Hello, World! program
To begin working with I/O, let's introduce a simple Go program.
Every .go file has this generic layout:
Package clause
Import declarations (optional)
Actual code
To compile and run your project, you need at least one .go file belonging to the main package with the main function. This function is an entry point for your application. We will use only one .go file in this topic — the main.go file.
We'll start with the famous Hello, World! program:
package main
import "fmt"
func main() {
fmt.Print("Hello, World!")
}All code examples below will show the body of the main function.
To try this example, you can copy it to the Go playground and press the Run button! And in case you already have Go installed on your computer, you can copy the above code to a main.go file and execute the go run main.go command in your terminal. If you want to try another example, don't forget to replace the body of the main function with new code.
Printing strings
Before moving on, we should become more confident in printing something simple on the screen. When you run a program, the program output (except error messages) goes to the standard output or stdout.
Writing to the stdout is the simplest way to see the results of your program. Programmers often use it for debugging purposes. Let's look at the Hello, World! program one more time. Here, we call the Print function from the fmt package:
fmt.Print("Hello, World!") // Writing "Hello, World!" to the stdoutFor multi-line printing, use the special symbol \n to escape the newline character and explicitly show where a new line begins:
fmt.Print("Hello, World!\n")
fmt.Print("This is my first Go program!\n")
// Output:
// Hello, World!
// This is my first Go program!In addition, there is a special function from this package that appends the newline character \n for us. We can rewrite the example above using the Println function:
fmt.Println("Hello, World!")
fmt.Println("This is my first Go program!")
// Output:
// Hello, World!
// This is my first Go program!Printing different variables
Now, Print and Println functions from the fmt package can print not only strings. As you progress, you will be able to format output in a sophisticated manner. But let's not get ahead of ourselves:
fmt.Println(true) // Printing type bool, will print true
fmt.Println(1023493) // Printing type int, will print 1023493
fmt.Println("my string") // Printing type string, will print my string
fmt.Println(12.4) // Printing type float, will print 12.4
fmt.Println('A') // Printing type rune, will print 65The rune type is an alias for the int32 type, so it is printed as an integer by default.
Print functions can also take several arguments and display them with space separation:
var boolean = true
var integer = 1023493
var str = "my string"
var float = 12.4
var character = 'A'
fmt.Println(boolean, integer, str, float, character)
// Output:
// true 1023493 my string 12.4 65Now, you've got enough information to create a simple program that will display text and numbers on the screen. Let's explore how we can read the input values to make the program more dynamic.
Reading the input
So far, we have only worked with sending data to the stdout. Now, let's see how we can obtain data from the standard input or stdin. The fmt.Scan function will help us with that; it takes as arguments pointers to variables that will further store the input data. It stores successive space-separated values in its consecutive arguments. Also, any new lines get counted as spaces:
var name string
fmt.Scan(&name) // Reading a string from the stdin into the name variable
fmt.Println(name) // Writing to the stdout the name you've entered
// in the previous stepIf you don't know yet what pointers are, don't be afraid of the Scan function. Just pay attention to the & symbol before every argument, as it is important.
Be aware of how the Scan function works with different types of variables:
var foo int // foo is 0
var str string // string is ""
fmt.Scan(&foo) // If you enter a string character, the scan function
// will leave the variable foo unchanged
fmt.Scan(&str) // If you enter an integer, it will be taken as a string
// and assigned to the variable strOften we will need to read several values at once. In this case, we define variables and then pass their pointers to Scan, separating them by a comma. In the example below, if we enter Alex 21, it'll first break the string into Alex and 21. Then, it will assign the former to the name variable and the latter to the age variable. You can play around with it, entering different strings:
var name string
var age string
fmt.Scan(&name, &age) // Reading from the stdin into the name and age variables
fmt.Println(name) // Writing to the stdout the value of the name variable
fmt.Println(age) // Writing to the stdout the value of the age variable Now, let's put together all we have learned so far and write a whole program!
Simple program with I/O
We can use the Scan function for reading from the stdin and the Print function for sending output to the stdout. In this program, we will read the user's name and age and write them to the stdout:
package main
import "fmt"
func main() {
var name string
var age int
fmt.Print("Enter your name: ") // Writing a request message to the stdout
fmt.Scan(&name) // Reading from the stdin into the name variable
fmt.Println("") // Going to the next line by writing /n to the stdout
fmt.Print("Enter your age: ") // Writing a request message to the stdout
fmt.Scan(&age) // Reading from the stdin into the age variable
fmt.Println("") // Going to the next line by writing /n to the stdout
fmt.Print(name, age) // Writing to the stdout the values of name and
// age variables that you have entered
}Conclusion
Here's what you know now:
What standard streams are;
How to write to the
stdoutusing thefmt.Print,fmt.Printlnfunctions;How to read from the
stdinusing thefmt.Scanfunction.
Now, you are ready to implement these skills in practice!