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.

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

报告相同问题?

悬赏问题

  • ¥30 关于用python写支付宝扫码付异步通知收不到的问题
  • ¥50 vue组件中无法正确接收并处理axios请求
  • ¥15 隐藏系统界面pdf的打印、下载按钮
  • ¥15 MATLAB联合adams仿真卡死如何解决(代码模型无问题)
  • ¥15 基于pso参数优化的LightGBM分类模型
  • ¥15 安装Paddleocr时报错无法解决
  • ¥15 python中transformers可以正常下载,但是没有办法使用pipeline
  • ¥50 分布式追踪trace异常问题
  • ¥15 人在外地出差,速帮一点点
  • ¥15 如何使用canvas在图片上进行如下的标注,以下代码不起作用,如何修改