如何解决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\"),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
和and4ѭ。我无法解释为什么编译器认为您不是。
解决方法
正如@kostix所说,
m
是if
的本地内容。试试这个代码
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\"),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)
}
, 我认为您在那些“ 6”分支中声明的变量是这些分支的代码块的局部变量。幸运的是,这不是JavaScript。因此,只需在if
以上的位置声明变量,然后使用=
而不是:=
进行分配即可。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。