从Go中的另一个包中调用一个函数

时间:2014-10-01 13:04:44

标签: go

嗨,我是golang的新手。

我有两个文件main.go位于package main下,另一个文件包含一些名为functions的函数。

我的问题是:如何从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"
}

非常感谢你的帮助。

6 个答案:

答案 0 :(得分:33)

您可以通过导入路径导入包,并通过包名引用所有导出的符号(以大写字母开头的那些符号),如下所示:

import "MyProj/functions"

functions.GetValue()

答案 1 :(得分:8)

  • 您应该在main.go中为导入添加前缀:MyProj,因为代码所在的目录是Go中默认的包名称,无论您是否正在调用它{{1 }} 或不。它将命名为main

  • MyProj仅表示此文件具有包含package main的可执行命令。然后,您可以将此代码运行为:func main()。有关详细信息,请参阅here

  • 您应该将go run main.go包中的func getValue()重命名为functions,因为只有这样,其他包才能看到func。有关详细信息,请参阅here

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

func GetValue()

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

package main

import (
    "fmt"
    "MyProj/functions"
)

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

答案 2 :(得分:3)

通过将函数名称first的第一个字符,GetValue

导出函数getValue

答案 3 :(得分:1)

  • 您需要在项目的根目录中创建一个 go.mod 文件:go mod init module_name
  • 暴露的函数名应该以大写字母开头
    import(
       "module_name/functions" 
    )
    func main(){
      functions.SomeFunction()
    }

答案 4 :(得分:0)

您可以写

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

如果您使用gopath进行编写,请编写此导入functions "MyProj/functions",或者您正在使用Docker

答案 5 :(得分:-1)

在Go软件包中,如果标识符名称的第一个字母以大写字母开头,则所有标识符都将导出到其他软件包。

=>将getValue()更改为GetValue()

相关问题