Go编译器未定义的方法

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

Go compiler undefined method

问题

我遇到了一个编译错误:"w.Write未定义(类型rest.ResponseWriter没有Write字段或方法)"

我创建了一个简单的测试文件,也遇到了同样的问题:

package server

import (
    "github.com/ant0ine/go-json-rest/rest"
)

func WriteTest(w rest.ResponseWriter) {
    var bs []byte
    w.Write(bs)
}

编译器说未定义的方法确实在rest包中。

英文:

I am getting a compiler error "w.Write undefined (type rest.ResponseWriter has no field or method Write)"

I created a bare bones test file and have the same problem:

package server

import (
        "github.com/ant0ine/go-json-rest/rest"
)

func WriteTest(w rest.ResponseWriter) {
        var bs []byte
        w.Write(bs)
}

The method that the compiler says is not defined is definitely in the rest package.

答案1

得分: 6

The rest.ResponseWriter类型没有Write方法,它有以下方法:

Header
WriteJson
EncodeJson
WriteHeader

然而,它在注释中提到,可以通过类型断言来使用http.ResponseWriter的方法。所以你可以尝试写下面的代码:

package server

import (
        "github.com/ant0ine/go-json-rest/rest"
        "net/http"
)

func WriteTest(w rest.ResponseWriter) {
        var bs []byte
        w.(http.ResponseWriter).Write(bs)
}
英文:

The rest.ReponseWriter type has no Write, it has the following methods:

Header
WriteJson
EncodeJson
WriteHeader

However, it says in the comments that http.ResponseWriter methods are available by type assertion. So you should be able to write the following:

package server

import (
        "github.com/ant0ine/go-json-rest/rest"
        "net/http"
)

func WriteTest(w rest.ResponseWriter) {
        var bs []byte
        w.(http.ResponseWriter).Write(bs)
}

1: https://github.com/ant0ine/go-json-rest/blob/master/rest/response.go "in the comments"

答案2

得分: 2

WriteresponseWriter 上定义。注意小写的 r

英文:

Write is defined on responseWriter. Note the lowercase r.

huangapple
  • 本文由 发表于 2015年10月7日 09:21:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/32982279.html
匿名

发表评论

匿名网友

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

确定