如何用Go语言从另一个文件调用函数?


107

我想从go lang中的另一个文件中调用函数,有什么可以帮助吗?

test1.go

package main

func main() {
    demo()
}

test2.go

package main

import "fmt"

func main() {
}

func demo() {
    fmt.Println("HI")
}

如何调用demotest2test1


你是什么意思go fmt?像在终端还是什么?这表明他在乎什么呢?
查理·帕克

Answers:


77

main的包裹中不能超过一个。

通常,包中给定名称的功能不能超过一个。

删除mainin test2.go并编译应用程序。该demo功能将从中可见test1.go


1
main在test2.go中删除后,我可以构建并运行,但是go run test1.go仍然无法运行test1.go 。为什么呢
Jeff Li

87
go run test1.go test2.go
Rich Churcher 2013年

2
@RichChurcher,您给出了答案。谢谢 。你也应该大写演示() ,公共职能上由常规套管
雷蒙德尚翁

如果test2具有结构,是否也会导入?
Angger

@RaymondChenon仅当需要在其他程序包中使用函数时才需要大写。在这种情况下,由于两个文件都在同一包“ main”中,因此它们也可以访问“ non-exported”(读取私有)功能。参见tour.golang.org/basics/3
与Sinojia见面

49

默认情况下,Go Lang仅构建/运行提到的文件。要链接所有文件,您需要在运行时指定所有文件的名称。

运行以下两个命令之一:

$go run test1.go test2.go. //order of file doesn't matter
$go run *.go

如果要构建它们,则应该做类似的事情。


1
开门见山。谢谢!
Russo

37

我在找同样的东西。要回答您的问题“ 如何从test1调用test2中的demo? ”,这就是我的方法。使用go run test1.go命令运行此代码。更改current_folder文件夹,其中test1.go是。

test1.go

package main

import (
    L "./lib"
)

func main() {
    L.Demo()
}

lib \ test2.go

将test2.go文件放在子文件夹中 lib

package lib

import "fmt"

// This func must be Exported, Capitalized, and comment added.
func Demo() {
    fmt.Println("HI")
}

5
确保方法名称大写,否则将无法使用。
最高

1
谢谢您的解决方案,它对我有很大的帮助!:)
jenkizenki

抱歉,但这显然行不通:package lib; expected main
Madeo

0

如果您只是运行go run test1.go而该文件引用了同一软件包中另一个文件中的函数,则它将出错,因为您没有告诉Go运行整个软件包,而是告诉它仅运行该文件。

您可以通过以下几种方式将文件分组为一个包,从而告诉go作为一个整体包运行。以下是一些示例(如果您的终端位于软件包的目录中):

go run ./

要么

go run test1.go test2.go

要么

go run *.go

您可以使用build命令获得相同的行为,并且在运行后,所创建的可执行文件将作为分组程序包运行,其中文件了解彼此的功能,等等。示例:

go build ./

要么

go build test1.go test2.go

要么

go build *.go

然后,当您将所有文件作为一个整体打包在一起运行时,从命令行简单地调用可执行文件将为您提供与使用run命令类似的输出。例如:

./test1

或任何可执行文件名在创建时都会被调用。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.