簡體   English   中英

在 Go 中從另一個包調用函數

[英]Call a function from another package in Go

我有兩個文件main.gopackage main ,另一個文件在包中包含一些函數,稱為函數。

我的問題是:如何從package main調用函數?

文件 1:main.go(位於 MyProj/main.go)

package main

import "fmt"
import "functions" // I dont have problem creating the reference here

func main(){
    c:= functions.getValue() // <---- this is I want to do
}

文件 2:functions.go(位於 MyProj/functions/functions.go)

package functions

func getValue() string{
    return "Hello from this another package"
}

您可以通過其導入路徑導入包,並通過包名稱引用其所有導出的符號(以大寫字母開頭的符號),如下所示:

import "MyProj/functions"

functions.GetValue()
  • 您應該在main.go為您的導入main.go前綴: MyProj ,因為代碼所在的目錄在 Go 中默認是一個包名,無論您是否稱其為main 它將被命名為MyProj

  • package main只是表示這個文件有一個包含func main()的可執行命令。 然后,您可以運行此代碼: go run main.go 請參閱此處了解更多信息。

  • 您應該將functions包中的func getValue()重命名為func GetValue() ,因為只有這樣,其他包才能看到 func。 請參閱此處了解更多信息。

文件 1:main.go(位於 MyProj/main.go)

package main

import (
    "fmt"
    "MyProj/functions"
)

func main(){
    fmt.Println(functions.GetValue())
}

文件 2:functions.go(位於 MyProj/functions/functions.go)

package functions

// `getValue` should be `GetValue` to be exposed to other packages.
// It should start with a capital letter.
func GetValue() string{
    return "Hello from this another package"
}

通過將函數名稱的第一個字符 GetValue 設為大寫來導出函數 getValue

你可以寫

import(
  functions "./functions" 
)
func main(){
  c:= functions.getValue() <-
}

如果您在gopath編寫此導入functions "MyProj/functions"或者您正在使用 Docker

在 Go 包中,如果標識符名稱的第一個字母以大寫字母開頭,則所有標識符都將導出到其他包。

=> 將 getValue() 更改為 GetValue()

  • 你需要在你的項目根目錄下創建一個go.mod文件: go mod init module_name
  • 暴露函數的名稱應以大寫字母開頭
    import(
       "module_name/functions" 
    )
    func main(){
      functions.GetValue()
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM