首先先到Go的官網下載並造官網的步驟安裝.
Mac 安裝好的路徑會在
/usr/local/go
修改 ~/.bash_profile
export GOPATH=/usr/local/go
export PATH=$JAVA_HOME/bin:$SCALA_HOME/bin:$GOPATH/bin:$PATH:~/bin
改完後重新讀取一下
source ~/.bash_profile
mkdir goHello
目錄結構如下
goHello
-src
-hello
hello.go
寫一隻 hello.go
package main
import "fmt"
func main() {
fmt.Println("Hello World")
}
daniel@Danielde-MacBook-Pro > /Volumes/Transcend/golang/goHello/src/hello > go run hello.go
warning: GOPATH set to GOROOT (/usr/local/go) has no effect
Hello World
2.先編譯後再執行
daniel@Danielde-MacBook-Pro > /Volumes/Transcend/golang/goHello/src/hello > go build hello.go
warning: GOPATH set to GOROOT (/usr/local/go) has no effect
daniel@Danielde-MacBook-Pro > /Volumes/Transcend/golang/goHello/src/hello > ll
total 4352
-rwxrwxrwx 1 daniel staff 1.9M 10 1 23:13 hello
-rwxrwxrwx 1 daniel staff 71B 10 1 23:13 hello.go
編譯出來的可執行檔直接 run 即可
daniel@Danielde-MacBook-Pro > /Volumes/Transcend/golang/goHello/src/hello > ./hello
Hello World
修改 hello.go,需要 import os 套件
package main
import (
"fmt"
"os"
)
func main() {
var name = os.Args[1]
fmt.Println("Hello " + name)
}
執行成功
daniel@Danielde-MacBook-Pro > /Volumes/Transcend/golang/goHello/src/hello > go run hello.go Daniel
warning: GOPATH set to GOROOT (/usr/local/go) has no effect
Hello Daniel