Skip to main content

Golang快速入門-5

export/unexport(private/public)

在golang中,如果要實現private/public的話,則需要使用到golang中的export/unexport,而這個要注意幾個事情

  1. 決定有沒有export/unexport是決定在你的檔案有沒有在同一個資料夾
  2. 如果希望export,則要將你希望export的type/interface/function/method/properity的第一個字變成大寫,才能跨資料夾做使用
  3. 在同一個資料夾中的package名稱皆要相同,但不一定要與資料夾名稱相同(但通常會相同)
  4. 在同個資料夾中的所有宣告在最外層的變數,皆可跨檔案存取(無論exported/unexported)
  5. 在import其他資料夾的時候,golang編譯器會自動將上述import的路徑下的package名稱當作你下面預設呼叫的來源別稱,如果需要另外命名可以在import前加上你希望的別名(但通常會將資料夾名稱與package名稱取相同,方便辨識) 檔案路徑/test/util.go
package util

import (
"fmt"
)

func Print() {
fmt.Println("hello")
}

如果需import上述的檔案,下面兩種方式皆可

package main

import (
"first-project/test"
)

func main() {
util.Print()
}

或是

package main

import (
test "first-project/test"
)

func main() {
test.Print()
}

範例

以下內容會放在下述連結中,可搭配觀看 https://github.com/kevinyay945/ithelp-2021/tree/master/go-package 我在其中建立了以下檔案 主程式為main.go,而我在裡面做了幾件事 呼叫util裡的 PrintHelloWorld() 並把裡面宣告的 util.ExportedVar util.Var1.ExportedProperty util.Var1.unexportedProperty util.unexportedVar 印出 但在最下面兩句,會發生取不到unexported的值 可以試著將下面兩句註解解開,看看有什麼錯誤發生