Before studying the Golang IO library, there are lots of functions in the IO library but the most important ones are 2 function interfaces, namely Reader
and Writer
. Reader
is usually used to read data from a file or some provided input/output. Meanwhile Writer
is a function that will later write data to a file or input/output provided by our system.
Reader
interface
This Reader Interface has many types of function implementers, but what we will try is a reader that is taken from a file. We can see the code example below.
package main
import (
"fmt"
"io/ioutil"
"log"
"os"
)
func main() {
f, err := os.Open("file.txt")
if err != nil {
log.Fatal("program broke")
}
defer f.Close()
bs, err := ioutil.ReadAll(f)
if err != nil {
log.Fatal("program read broke")
}
fmt.Println(bs)
fmt.Println(string(bs))
}
And the contents of the file.txt
file are as follows
Hello World
After we look at the code above, we can imagine that os.Open
is a function used to open and search for files so that later we can read the data using the ioutil.ReadAll(f)
function.
If we look at the code above, the return from the ioutil.ReadAll
function is captured by the variable bs
which we will print and display its contents. By default, the bs
variable has a data type of byte
so we need to add the string(bs)
function so that it can be read.
Writer
interface
The Writer
interface is used so that we can write to one file or several files at once. We will try to look at the code below, a basic example of using the Writer
interface
package main
import (
"log"
"os"
)
func main() {
dst, err := os.Create("create.txt")
if err != nil {
log.Fatal("program broke")
}
defer dst.Close()
bs := []byte("hello world, Santekno")
_, err = dst.Write(bs)
if err != nil {
log.Fatal("program broke")
}
}
If we run the program above, a create.txt
file will be created with the contents of the file in the form of the string hello world, Santekno
. This program is simple where we can find out what name the file was created and what we can control the contents of the file.