To create a file in Go, you need to import the os
package and call the Create()
function, which takes the name of the file you want to create as an argument, and returns a pointer to a File
object. Here's an example:
main.go631 chars26 lines
This code creates a new file named "example.txt" in the current directory, writes the string "Hello, world!" to it, then closes the file. If an error occurs at any point, the code prints the error and exits.
Note that it's important to always close the file when you're done with it, to free up system resources and make sure your changes are written to disk. You can use the defer
keyword to make sure the file is closed automatically when the function exits, as shown in the example.
gistlibby LogSnag