dream198731
2015-03-26 02:29 浏览 76
已采纳

布尔值设置为true会无意更改为false

In my golang application, I'm setting some global variables to true based on form input, and then discovering that they have changed to false when used in a subsequent function. Question, what is the proper way to declare and set Boolean values in golang?

var withKetchup bool
var withMustard bool

func orderProcess(w http.ResponseWriter, r *http.Request){

     r.ParseForm()
     withKetchup := r.FormValue("withKetchup")  //set to true (in form js form selection)
     withMustard := r.FormValue("withMustard")  //set to true

      code omitted ///
}

func prepareOrder(){

      code omitted//
     fmt.Println(withKetchup, withMustard) //both are false even though initially set to true
     if withKetchup == true && withMustard == true{

     }else {

     }


}
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答 默认 最新

  • 已采纳
    dongsha2792 dongsha2792 2015-03-26 02:36

    The code

     withKetchup := r.FormValue("withKetchup") 
    

    declares and sets a local variable of type string using a short variable declaration. To set the global bool variable, convert the statement to an assignment by removing the ":". Also, compute a bool value by comparing the form value with "":

     withKetchup = r.FormValue("withKetchup") == "true"
    

    Because the server executes handlers concurrently, it's not safe to use a global variable like this. I suggest passing the values as arguments to prepareOrder:

    func orderProcess(w http.ResponseWriter, r *http.Request){
    
         r.ParseForm()
         withKetchup := r.FormValue("withKetchup") == "true"
         withMustard := r.FormValue("withMustard") == "true"
         prepareOrder(withKetchup, withMustard)
    }
    
    func prepareOrder(withKetchup, withMustard bool){
         if withKetchup == true && withMustard == true{
    
         }else {
    
         }
    }
    
    点赞 评论 复制链接分享

相关推荐