去编译器未定义的方法
问题描述:
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.
我遇到了编译器错误“ w.Write undefined(类型rest.ResponseWriter没有字段或方法Write)” p>
我创建了一个简单的测试文件,并遇到了相同的问题: p>
package server
import(
“ github。 com / ant0ine / go-json-rest / rest“
)
func WriteTest(w rest.ResponseWriter){
var bs [] byte
w.Write(bs)
}
code > pre>
编译器所说的未定义方法肯定在休息包。 p>
div>
答
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)
}
答
Write
is defined on responseWriter
. Note the lowercase r
.