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条)

报告相同问题?

悬赏问题

  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥170 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上