繁体   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