Reading and writing files is a key part of most applications. In Golang, it’s not quite as straightforward as with other languages like Python, but let’s go through it line by line to understand how it all works. First off, let’s go through writing a file.
If you look at the Golang documentation for writing files, you’ll see the below.
This tell us how to structure our request. So, we need to pass in the filename we want to save, we need to pass in the data to save in byte slice format (a slice of bytes) and we need to define the permissions for the file.
So, if we have a custom type called ‘foods’, which is a slice of strings, then we need to convert that data type into a slice of bytes. The first step in doing that is to convert the deck to be a slice of strings:
Now, we write a new function which calls the WriteFile function. We pass in a filename as a string parameter to the function and we use that in the WriteFile definition. Now to convert our foods input into a slice of bytes, we use this syntax byte(thing to convert). This is going to convert the thing in the brackets to be of type byteslice.
You can now run your code and check your project folder and you’ll see your new file has been created. Now, let’s read it in.
Here, let’s go through what is going on:
- we create a function call ReadFile which has a filename passed into it. It will return one of our datatype of foods (which is a slice of strings)
- We then set two variables, one is ‘out’ which is the contents of the file and the other is ‘err’ which is the error (if there is one)
- We then handle an error – if the err variable isn’t empty, then create an error. We can force the script to exit at this point with os.Exit. The code inside can be whatever you want it to be (except 0, which means everything is fine). This means you could have your own error code definitions.
- If there are no errors, we convert the byte slice data format from within the file into a string
- We then use the strings function to split the string by commas
- We then convert that into our datatype of foods and return it