Handling Common Data Formats in Go (TXT)

Tom Deneire
3 min readOct 15, 2022
Photo by Alina Grubnyak on Unsplash

Reading and writing data is one of the basic elements of programming. In Go, which is a compiled language with strong typing, this might seem somewhat more complicated than other languages like Python. Here’s how to handle the most common data formats like a true Gopher…

Text

“Data” does not necessarily have to be structured data. A plain .txt file (or any file format really) can be a legitimate source of data. Although opening a file and reading its contents may seem like a trivial enough task, there are still several ways to do this in Go.

Reading a whole file

One way is to read a complete file into memory, so this is only an option when you know a file is going to be limited in size (like configuration files and such).

The canonical way to do this, is to use os.ReadFile (before Go 1.16 there was also ioutil.ReadFile , which is now deprecated)

Output:

Hello
world

Reading a file bit by bit

--

--