環境變數是一種用於將組態資訊傳遞到Unix程式的通用機制。我們來看看如何設定,獲取和列出環境變數。
所有的範例程式碼,都放在
F:\worksp\golang
目錄下。安裝Go程式設計環境請參考:/2/23/798.html
command-line-flags.go
的完整程式碼如下所示 -
package main
import "os"
import "strings"
import "fmt"
func main() {
// To set a key/value pair, use `os.Setenv`. To get a
// value for a key, use `os.Getenv`. This will return
// an empty string if the key isn't present in the
// environment.
os.Setenv("FOO", "1")
fmt.Println("FOO:", os.Getenv("FOO"))
fmt.Println("BAR:", os.Getenv("BAR"))
// Use `os.Environ` to list all key/value pairs in the
// environment. This returns a slice of strings in the
// form `KEY=value`. You can `strings.Split` them to
// get the key and value. Here we print all the keys.
fmt.Println()
for _, e := range os.Environ() {
pair := strings.Split(e, "=")
fmt.Println(pair[0])
}
}
執行上面程式碼,將得到以下輸出結果 -
F:\worksp\golang>go run environment-variables.go
FOO: 1
BAR:
ALLUSERSPROFILE
ANDROID_HOME
APPDATA
asl.log
CommonProgramFiles
CommonProgramFiles(x86)
CommonProgramW6432
COMMPath
COMPUTERNAME
ComSpec
FOO
FPS_BROWSER_APP_PROFILE_STRING
FPS_BROWSER_USER_PROFILE_STRING
FP_NO_HOST_CHECK
GOROOT
HOMEDRIVE
HOMEPATH
JAVA_HOME
LOCALAPPDATA
LOGONSERVER
M2_HOME
MAVEN_HOME
MYSQLCONNECTOR_ASSEMBLIESPATH
NUMBER_OF_PROCESSORS
OPENSSL_CONF
OS
Path
PATHEXT
PROCESSOR_ARCHITECTURE
PROCESSOR_IDENTIFIER
PROCESSOR_LEVEL
PROCESSOR_REVISION
ProgramData
ProgramFiles
ProgramFiles(x86)
ProgramW6432
PROMPT
PSModulePath
PUBLIC
SESSIONNAME
SystemDrive
SystemRoot
TEMP
TMP
USERDOMAIN
USERDOMAIN_ROAMINGPROFILE
USERNAME
USERPROFILE
VS140COMNTOOLS
windir
windows_tracing_flags
windows_tracing_logfile