2014-04-21 18 views
4

我需要在我的代碼中使用config,我想從命令行加載配置路徑。 我嘗試:如何在golang中正確使用os.Args?

if len(os.Args) > 1 { 
     configpath := os.Args[1] 
     fmt.Println("1") // For debug 
    } else { 
     configpath := "/etc/buildozer/config" 
     fmt.Println("2") 
    } 

然後我用的配置:

configuration := config.ConfigParser(configpath) 

當我與參數啓動我去文件(或沒有)我收到類似的錯誤

# command-line-arguments 
src/2rl/buildozer/buildozer.go:21: undefined: configpath 

我應該怎樣正確使用os.Args?

回答

7

定義configPath超出您的if的範圍。

configPath := "" 

if len(os.Args) > 1 { 
    configpath = os.Args[1] 
    fmt.Println("1") // For debug 
} else { 
    configpath = "/etc/buildozer/config" 
    fmt.Println("2") 
} 

注意if內的 'configPath ='(而不是:=)。

那樣configPath在之前被定義並且在if之後仍然可見。

查看更多「Declarations and scope」/「Variable declarations」。

+0

非常感謝!它解決了我的問題。 –