Reading user input or writing to a file are some of the basic input/output (IO) operations developers need to perform as they get started with programming in Go. There are basically three packages involved in I/O operations in Golang: fmt, os, and bufio. This Go programming tutorial provides some coding examples about some of the specifics used in relation to performing basic I/O operations with Golang.
Basic Input Examples Using Go
To get user input through the console in Go, developers can use one of the several functions available in the fmt package. They are as follows:
func Scan(a …any) (n int, err error)
The Scan function reads values from the console and stores them into variables passed as a comma-separated argument, successively. It stops scanning when a newline is encountered. The function returns the number of items scanned. An error is reported if the number of arguments do not match with the number of items input.
func Scanf(format string, a …any) (n int, err error)
The Scanf function also acts as the Scan function, but here we supply the format string where the newlines in the input must match with the newlines in the format supplied. Note that here, with %c in the format string, we can scan the next rune in the input. The rune can be a space, tab, or a newline.
func Scanln(a …any) (n int, err error)
Scanln is the same as Scan except that it stops if a newline or EOF is encountered.
func Sscan(str string, a …any) (n int, err error)
Sscan is similar to Scan but here, newline is counted as a space.
func Sscanf(str string, format string, a …any) (n int, err error)
Sscanf takes the input according to the format supplied and returns the number of items parsed.
func Sscanln(str string, a …any) (n int, err error)
Sscanln is similar to Sscan, but it stops at newline.
Here is an example Go code snippet demonstrating how to accept input from a user using Go:
var ( id int name string salary float32 input = “name/11/34.67” format = “%d/%s/%f” ) fmt.Scanln(&id, &name, &salary) fmt.Scanf(“%d, %s , %f”, &id, &name, &salary) fmt.Sscanf(input, format, &id, &name, &salary)
Go programmers can capture the number of arguments read and input errors as follows:
argc, err := fmt.Scanln(&id, &name, &salary)
Reading: Database Programming in Go
Basic Output Operations in Go
To print into the standard output, developers can use one of the many print methods in the fmt package. Some common print methods in Go include:
func Print(a …any) (n int, err error)
This method is used to write in the standard output. It returns the number of bytes written and error information in the printing process. We can supply comma-separated arguments with this method.
func Printf(format string, a …any) (n int, err error)
This method prints in the standard output according to the format specifier and returns the number of bytes written along with error information if any.
func Println(a …any) (n int, err error)
This method is similar to the print method except that a newline is always appended to the end of the printed value.
Here is an example snippet showing basic output operations in Golang:
stringVal := “hello” intVal := 12345 floatVal := 4567.787 fmt.Print(stringVal, intVal, floatVal) fmt.Println(stringVal, intVal, floatVal) fmt.Printf(“%s, %d, %f”, stringVal , intVal, floatVal)
Reading: An Introduction to File Handling in Go
Buffered IO Operations in Go Programming
Buffered IO is a technique that stores the result temporarily in a buffer/memory before transmission can occur. This technique is particularly useful for increasing the speed of the program by reducing invocation to low-level system calls, because system calls are inherently slow.
The Golang library supplies another package called bufio. We also can use it to get users. The bufio package implements buffered IO by wrapping the io.Reader object:
var reader *bufio.Reader reader = bufio.NewReader(os.Stdin) fmt.Println(“Enter your name: “) in, err := reader.ReadString(‘n’)
In the example above we have created a pointer to the Reader type using the function bufio.NewReader. The object is linked to the console input through os.Stdin, passed as an argument to the NewReader. The reader has several methods for reading input, like ReadByte, ReadSlice, ReadRune, etc, to read specific types of input. Here we have used the ReadString method, which takes a byte as a delimiter.
The ReadString method reads string values or nil for the error and reads until the EOF or the supplied delimiter is reached.
Similar to input, there can be buffered output to the screen. This is done with the bufio.NewWriter method, as follows:
msg := “hello” var writer *bufio.Writer writer = bufio.NewWriter(os.Stdout) defer writer.Flush() writer.WriteString(msg)
The code is self-explanatory, similar to reading from standard input except that here we are using Writer object.
Reading: How to Use Pointers in Go
File IO Operations Using Go
Go files are represented by file handles. File handles are nothing but pointers to objects of type os.File. In fact, the standard input os.Stdin and standard output os.Stdout we used in previous examples are nothing but os.File types. So, in like fashion, we also can read and write to any file using methods in the bufio package.
Here is a quick example:
package main import ( “bufio” “fmt” “os” ) func readFromFile(fileName string) { inFile, err := os.Open(fileName) if err != nil { panic(err) } defer inFile.Close() reader := bufio.NewReader(inFile) b := make([]byte, 32) for { i, err := reader.Read(b) if err != nil { fmt.Println(err) break } fmt.Println(string(b[:i])) } } func writeToFile(text []string, fileName string) { file, err := os.Create(fileName) if err != nil { fmt.Println(err) } writer := bufio.NewWriter(file) defer writer.Flush() for _, line : = range text { b, err := writer.WriteString(line) if err != nil { fmt.Println(err) } fmt.Println(“Bytes: “, b) } } func main() { text := []string{“This is a sample program”, ” that demonstrates “, ” file handling “} writeToFile(text, “sample.dat”) readFromFile(“sample.dat”) }
Final Thoughts on IO Operations in Golang
Implementing IO operations in Go is pretty simple and straightforward. As we can see, there are different ways to implement IO. The fmt package provides ample methods for basic input and output operations. If we want to implement buffered IO, bufio is the package to use. Note that here, we have given only the basic idea, there are several functions and methods in each of the packages that help in doing IO operations with standard IO or files.
read more Go and Golang programming tutorials.