duandou8457 2014-04-26 03:56
浏览 22
已采纳

Golang网络编程教程代码不起作用

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条回答 默认 最新

  • duanmuybrtg1231 2014-04-26 04:11
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?