Go编译器说“已声明且未使用”。但他们正在被使用 [英] Go compiler says "declared and not used" but they are being used
本文介绍了Go编译器说“已声明且未使用”。但他们正在被使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下函数给我变量已声明且未使用错误:
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)
}
它给我以下错误:
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
都在使用。我无法确定为什么编译器认为您不是。
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.
推荐答案
正如@kostix所说, m
是本地的, if
。尝试使用此代码
As @kostix said, m
is local to the scope of the if
. Try this code
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)
// NOTE! now m is in the function's scope
var m Image
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)
}
这篇关于Go编译器说“已声明且未使用”。但他们正在被使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文