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 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀