douning5041 2018-10-24 05:01
浏览 94
已采纳

声明且未使用-如何在IF语句中更新变量

I am trying to setup a bool variable with a default value and update it based on a condition, in Go Lang. The func foo compiles, But the function bar doesn't compile and gives an error "f declared and not used"

There is a related answer - which doesn't explain the next question

What is the correct pattern for this(bar function) in Go?

Here is the code:

package main

import (
"fmt"
"strconv"
)

func foo(m map[string]string) bool {
    f := false

if _, exists := m["READWRITE"]; exists {
    fmt.Println("Before Updating f : ", f)
    f, _ = strconv.ParseBool(m["READWRITE"])
    //if err != nil {
    //  panic(err)
    //}
}

fmt.Println("After Updating f : ", f)

return f
}

func bar(m map[string]string) bool {
    f := false

    if _, exists := m["READWRITE"]; exists {
         fmt.Println("Before Updating f : ", f)
         f, err := strconv.ParseBool(m["READWRITE"]) // error on this line "f declared and not used"
        if err != nil {
            panic(err)
        }
    }

    fmt.Println("After Updating f : ", f)

    return f
}

func main() {
    m := map[string]string{"READWRITE": "true"}

    fmt.Println(foo(m))
    fmt.Println(bar(m))
}
  • 写回答

3条回答 默认 最新

  • douzhan1963 2018-10-24 07:10
    关注

    gives an error "f declared and not used"

    f in your sample is a newly-declared variable. Its scope lies within the if block, and is different from the one originally declared at the start of your main().

    Here is a sample commented code that may help clarify (also available as a runnable Go Playground snippet):

    package main
    
    import (
        "fmt"
    )
    
    func main() {
        food := "burger"                 // (1) variable 'food' is declared
        fmt.Println("food is", food)     // OUTPUT: "burger"
    
        if true {
            food := "fries"              // (2) a new 'food' variable is a declared here. it shadows the one in (1)
            fmt.Println("food is", food) // this accesses the 'food' var from (2). OUTPUT: "fries"
        }
    
        fmt.Println("food is", food)     // this accesses the variable from (1). OUTPUT: "burger"
    }
    

    Hope this helps clarify. Cheers,

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 matlab计算中误差
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊