Question

I'm trying to learn Go for web programming. I've been learning the language, and I've recently started this tutorial on the official site for the go language.

So far, I'm stuck on the Data Structures part. I've copied the code word for word.

Here's the code:

package main

import (
        "fmt"
        "io/ioutil"
)

type Page struct {
        Title string
        Body []byte
}

func (p *Page) save() (error) {
        filename := p.Title + ".txt"
        return ioutil.WriteFile(filename, p.Body, 0600)
}

func loadPage(title string) (*Page, error) {
        filename := title + ".txt"
        body, err := ioutil.ReadFile(filename)
        if err != nil {
                return nil, err
        }

        return &Page{Title: title, Body: body}, nil
}

func main() {
        p1 := &Page{Title: "TestPage", Body: []byte("WHADDUP!")}
        p1.save
        p2, _ := loadPage("TestPage")
        fmt.Println(string(p2.Body))
}

Running $ go build wiki.go gives me the following:

# command-line arguments
./main.go:30: p1.save evaluated but not used

What is it that I have wrong? It seems to me like I've copied the code word for word, except for the string that's saved to the file.

Was it helpful?

Solution

p1.save is a function so, written like this, it doesn't do anything, which is what the compiler is "warning" you about (but with Go, what could be a warning is in fact an error and prevents compilation).

What you might want is p1.save(), which unlike p1.save would actually run the function.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top