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 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥50 我撰写的python爬虫爬不了 要爬的网址有反爬机制
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等