2017-12-28 9 views
-3

を反映していないグローバル変数を行く私は、次のコード正しい値

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

を持っていますが、出力は次のとおりです。

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

すなわち。関数something()はグローバル変数を認識していますが、その真の値を反映していないようです。これはゴーランでの私の最初の試みです。私は間違って何をしていますか?

+7

':='を使用したので、グローバル変数をシャドウするローカル変数です。既存の変数への代入には '='を使います。 – Carpetsmoker

答えて

2

問題はこの行がmainです。

outputOnly := *vmoutputonlyPtr 

:=、左側に新しい変数を宣言outputOnly、右側の式のタイプの、*vmoutputonlyPtrとそれに式を割り当てます。これは、その範囲内

var outputOnly bool = *vmoutputonlyPtr 

この新しいoutputOnly"shadows"グローバルoutputOnly ...と等価です。だからoutputOnly := *vmoutputonlyPtrの後のすべてのコードはmainにあり、これはmainにローカルであるoutputOnlyを指しています。 something()は、グローバルoutputOnlyを指します。 Goの可変シャドーイングについての詳細は、

See Redeclaration and Reassignment in Effective Goです。

既存の変数に割り当てる場合は、=を使用してください。

outputOnly = *vmoutputonlyPtr 
関連する問題