×

go · level 2 · unit 6 · lesson 1

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

A keeps your data after the boxes are gone.

Everything in your boxes vanishes when the program ends. A file keeps data saved, like a page in a notebook. On Gwecode every run starts in its own empty folder, so the files you make last for that run only.

saves text into a file. Files hold bytes, so []byte(text) turns the string into a first. 0644 says who may read and change the file: use it every time.

reads the whole file back as a byte slice, and string(data) turns it into text. Both commands return an error value, because files go missing. errors.Is(err, os.ErrNotExist) spots a missing one.

package main
import "fmt"
import "os"
func main() {
	err := os.WriteFile("notes.txt", []byte("Feed the cat\nBuy milk\n"), 0644)
	if err != nil {
		fmt.Println("Could not save:", err)
		return
	}
	data, err := os.ReadFile("notes.txt")
	if err != nil {
		fmt.Println("Could not read:", err)
		return
	}
	fmt.Print(string(data))
	fmt.Println(len(data), "bytes")
}

Writing to a file that already exists replaces everything that was in it.