Go编译器说“声明但未使用”,但它们正在被使用

时间:2011-05-30 14:55:02

标签: compiler-errors 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

事情是merrkey都在使用。我无法理解为什么编译器认为你的不是。

2 个答案:

答案 0 :(得分:2)

正如@kostix所说,mif范围的本地。试试这段代码

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)
}

答案 1 :(得分:1)

我认为你在那些if分支中声明的变量是这些分支的代码块的本地变量。这不是JavaScript(幸运的是)。因此,只需在if以上的位置声明您的变量,然后使用=代替:=分配给它们。