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

布尔值设置为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 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 {
    
         }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作