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 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化