Golang网络编程教程代码无法正常工作。

huangapple go评论87阅读模式
英文:

golang web programming tutorial code not working

问题

我正在尝试学习用于Web编程的Go语言。我一直在学习这门语言,最近开始学习官方网站上的这个教程。

到目前为止,我在数据结构部分遇到了困难。我已经逐字逐句地复制了代码。

以下是代码:

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))
}

运行$ go build wiki.go后,我得到了以下结果:

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

我错在哪里?在我看来,我已经逐字逐句地复制了代码,除了保存到文件的字符串不同。

英文:

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.

答案1

得分: 3

p1.save 是一个函数,所以写成这样的话,它不会执行任何操作,这也是编译器在“警告”你的内容(但在Go语言中,警告实际上是一个错误,会阻止编译)。

你可能想要的是 p1.save(),与 p1.save 不同的是,它会真正运行这个函数。

英文:

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.

huangapple
  • 本文由 发表于 2014年4月26日 11:56:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/23306456.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定