doumao6212 2017-12-28 20:52
浏览 34
已采纳

去全局变量不能反映正确的值

I have the following code

package main

import ( 
    "fmt"
    "flag"
)

var outputOnly bool


func something() string {
    if outputOnly {
        fmt.Println("outputting only")
    } else {
        fmt.Println("executing commands")
    }   
    return "blah"
}

func main() {

    vmoutputonlyPtr     := flag.Bool("outputonly",false,"If set it will only output the commands it would execute, naturally without the correct parameter values set.")
    flag.Parse()
    outputOnly          := *vmoutputonlyPtr 
    if outputOnly {
        fmt.Println("outputonly commands will not execute")
    }

    var blah string
    blah = something()
    fmt.Println("blah is " + blah)
}

But the output is this:

$ ./se -outputonly                       
outputonly commands will not execute
executing commands

ie. it appears that the function something() is aware of the global variable, but does not reflect its true value. This is my first attempt at golang. What am I doing wrong?

  • 写回答

1条回答 默认 最新

  • dotj6816 2017-12-28 21:07
    关注

    The problem is this line in main.

    outputOnly := *vmoutputonlyPtr 
    

    := declares a new variable on the left, outputOnly, of the type of the expression on the right, *vmoutputonlyPtr and assigns the expression to it. It's equivalent to...

    var outputOnly bool = *vmoutputonlyPtr
    

    This new outputOnly "shadows" your global outputOnly in its scope. So all the code after outputOnly := *vmoutputonlyPtr in main refers to this outputOnly local to main. While something() refers to the global outputOnly.

    See Redeclaration and Reassignment in Effective Go for more about variable shadowing in Go.

    If you want to assign to an existing variable, just use =.

    outputOnly = *vmoutputonlyPtr 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器