嗨我是新手在golang.
我有两个文件,main.go这就是下package 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
}
Run Code Online (Sandbox Code Playgroud)
文件2:functions.go(位于MyProj/functions/functions.go中)
package functions
func getValue() string{
return "Hello from this another package"
}
Run Code Online (Sandbox Code Playgroud)
非常感谢你的帮助.
Jim*_*imB 42
您通过其导入路径导入包,并通过包名称引用其所有导出的符号(以大写字母开头的符号),如下所示:
import "MyProj/functions"
functions.GetValue()
Run Code Online (Sandbox Code Playgroud)
Ina*_*mus 11
您应该在导入前main.go加上:MyProj,因为,无论您是否正在调用,代码所在的目录都是Go中的默认包名main.它将被命名为MyProj.
package main只表示该文件具有包含的可执行命令func main().然后,你可以运行此代码:go run main.go.有关详细信息,请参见此处
您应该将您的func getValue()in functions包重命名为func GetValue(),因为只有这样,func才会对其他包可见.有关详细信息,请参见此处
文件1:main.go(位于MyProj/main.go)
package main
import (
"fmt"
"MyProj/functions"
)
func main(){
fmt.Println(functions.GetValue())
}
Run Code Online (Sandbox Code Playgroud)
文件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"
}
Run Code Online (Sandbox Code Playgroud)
小智 5
你可以写
import(
functions "./functions"
)
func main(){
c:= functions.getValue() <-
}
Run Code Online (Sandbox Code Playgroud)
如果您写入gopath此导入functions "MyProj/functions"或者您正在使用 Docker
| 归档时间: |
|
| 查看次数: |
37241 次 |
| 最近记录: |