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屋!
查看全文