Go编译器说“已声明但未使用”但它们正在被使用
我有以下函数给我“声明变量但未使用”错误:
type Comparison struct {
Left []byte
Right []byte
Name string
}
func img(w http.ResponseWriter, r *http.Request, c appengine.Context, u *user.User) {
key := datastore.NewKey("Comparison", r.FormValue("id"), 0, nil)
side := r.FormValue("side")
comparison := new(Comparison)
err := datastore.Get(c, key, comparison)
check(err)
if( side == "left"){
m, _, err := image.Decode(bytes.NewBuffer(comparison.Left))
} else {
m, _, err := image.Decode(bytes.NewBuffer(comparison.Right))
}
check(err)
w.Header().Set("Content-type", "image/jpeg")
jpeg.Encode(w, m, nil)
}
它给我以下错误:
dpcompare.go:171: m declared and not used
dpcompare.go:171: err declared and not used
dpcompare.go:173: m declared and not used
dpcompare.go:173: err declared and not used
dpcompare.go:178: undefined: m
dpcompare.go:185: key declared and not used
事情是 m
、err
和 key
都被使用了。我无法理解为什么编译器认为你不是。
I have the following function that is giving me "variable declared and not used" errors:
type Comparison struct {
Left []byte
Right []byte
Name string
}
func img(w http.ResponseWriter, r *http.Request, c appengine.Context, u *user.User) {
key := datastore.NewKey("Comparison", r.FormValue("id"), 0, nil)
side := r.FormValue("side")
comparison := new(Comparison)
err := datastore.Get(c, key, comparison)
check(err)
if( side == "left"){
m, _, err := image.Decode(bytes.NewBuffer(comparison.Left))
} else {
m, _, err := image.Decode(bytes.NewBuffer(comparison.Right))
}
check(err)
w.Header().Set("Content-type", "image/jpeg")
jpeg.Encode(w, m, nil)
}
It gives me the following errors:
dpcompare.go:171: m declared and not used
dpcompare.go:171: err declared and not used
dpcompare.go:173: m declared and not used
dpcompare.go:173: err declared and not used
dpcompare.go:178: undefined: m
dpcompare.go:185: key declared and not used
The thing is m
, err
, and key
are all being used. I can't wrap my head around why the compiler thinks thy are not.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
正如@kostix所说,
m
对于if
的范围是本地的。试试这个代码As @kostix said,
m
is local to the scope of theif
. Try this code我认为您在这些
if
分支中声明的变量对于这些分支的代码块来说是本地的。这不是 JavaScript(幸运的是)。因此,只需在if
上方声明变量,并使用=
而不是:=
来分配给它们。I think the variables you declare in those
if
branches are local to the code blocks of these branches. This is not JavaScript (luckily). So just declare your variables somewhere aboveif
and use=
instead of:=
to assign to them.