iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 1
1
Software Development

學習Go系列 第 1

Go day 1 (Run Go)

  • 分享至 

  • twitterImage
  •  

下載安裝

首先先到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

建立 Go project

mkdir goHello

目錄結構如下

goHello  
 -src
  -hello
   hello.go

寫 Go 程式

寫一隻 hello.go

package main
import "fmt"
func main() {
  fmt.Println("Hello World")
}

Run Go

  1. 直接執行,用 go run
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

下一篇
Go day 2 (package main)
系列文
學習Go30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言