Go compiler says “declared and not used” but they are being used

前端 未结 2 1218
别跟我提以往
别跟我提以往 2020-12-12 01:37

I have the following function that is giving me \"variable declared and not used\" errors:

type Comparison struct {
        Left []byte
        Right []byte
         


        
相关标签:
2条回答
  • 2020-12-12 02:08

    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 above if and use = instead of := to assign to them.

    0 讨论(0)
  • 2020-12-12 02:16

    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)
    }
    
    0 讨论(0)
提交回复
热议问题