英文:
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
Write 在 responseWriter 上定义。注意小写的 r。
英文:
Write is defined on responseWriter. Note the lowercase r.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论