如何在Go中从另一个文件调用函数

huangapple go评论83阅读模式
英文:

How to call function from another file in Go

问题

如何从test1中调用test2中的demo函数?

英文:

I want to call function from another file in Go. Can any one help?

test1.go

package main

func main() {
	demo()
}

test2.go

package main

import "fmt"

func main() {
}

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

How to call demo in test2 from test1?

答案1

得分: 138

你的包中不能有多个main函数。

更一般地说,你的包中不能有多个同名的函数。

test2.go中移除main函数并编译应用程序。demo函数将可以从test1.go中访问到。

英文:

You can't have more than one main in your package.

More generally, you can't have more than one function with a given name in a package.

Remove the main in test2.go and compile the application. The demo function will be visible from test1.go.

答案2

得分: 119

Go Lang默认只构建/运行指定的文件。要链接所有文件,您需要在运行时指定所有文件的名称。

运行以下两个命令之一:

$go run test1.go test2.go. //文件的顺序无关紧要
$go run *.go

如果要构建它们,您应该执行类似的操作。

英文:

Go Lang by default builds/runs only the mentioned file. To Link all files you need to specify the name of all files while running.

Run either of below two commands:

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

You should do similar thing, if you want to build them.

答案3

得分: 60

我正在寻找同样的东西。为了回答你的问题“如何从test1中调用test2中的demo函数?”,这是我做的方法。使用go run test1.go命令运行这段代码。将current_folder更改为test1.go所在的folder

test1.go

package main

import (
	L "./lib"
)

func main() {
    L.Demo()
}

lib\test2.go

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

package lib

import "fmt"

// 这个函数必须是导出的,首字母大写,并添加注释。
func Demo() {
    fmt.Println("HI")
}
英文:

I was looking for the same thing. To answer your question "How to call demo in test2 from test1?", here is the way I did it. Run this code with go run test1.go command. Change the current_folder to folder where test1.go is.

test1.go

package main

import (
	L "./lib"
)

func main() {
    L.Demo()
}

lib\test2.go

Put test2.go file in subfolder lib

package lib

import "fmt"

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

答案4

得分: 16

main.go

package main

import "pathToProject/controllers"

func main() {
    controllers.Test()
}

control.go

package controllers

func Test() {
    // 做一些事情
}

永远不要忘记:可见的外部函数、变量和方法以大写字母开头。

例如:

func test() {
    // 我在文件外不可见
}
 
func Test() {
    // 我在文件外可见
}
英文:

A functional, objective, simple quick example:

main.go

package main

import "pathToProject/controllers"

func main() {
	controllers.Test()
}

control.go

package controllers

func Test() {
// Do Something
}

Don't ever forget: Visible External Functions, Variables and Methods starts with Capital Letter.

i.e:

func test() {
    // I am not Visible outside the file
}
 
func Test() {
    // I am VISIBLE OUTSIDE the FILE
}

答案5

得分: 10

如果你只运行go run test1.go,并且该文件引用了同一个包中另一个文件中的函数,那么会出错,因为你没有告诉Go运行整个包,而是告诉它只运行那个文件。

你可以通过多种方式将文件作为一个包在运行命令中告诉go运行整个包。以下是一些示例(如果你的终端在包的目录中):

go run ./

或者

go run test1.go test2.go

或者

go run *.go

你可以期望使用构建命令时会有相同的行为,运行创建的可执行文件将作为一个分组的包运行,其中文件知道彼此的函数等。示例:

go build ./

或者

go build test1.go test2.go

或者

go build *.go

然后之后只需从命令行调用可执行文件,就会得到与在运行所有文件作为一个整体包时使用运行命令时类似的输出。例如:

./test1

或者根据创建时的可执行文件名来命名。

英文:

If you just run go run test1.go and that file has a reference to a function in another file within the same package, it will error because you didn't tell Go to run the whole package, you told it to only run that one file.

You can tell go to run as a whole package by grouping the files as a package in the run commaned in several ways. Here are some examples (if your terminal is in the directory of your package):

go run ./

OR

go run test1.go test2.go

OR

go run *.go

You can expect the same behavior using the build command, and after running the executable created will run as a grouped package, where the files know about eachothers functions, etc. Example:

go build ./

OR

go build test1.go test2.go

OR

go build *.go

And then afterward simply calling the executable from the command line will give you a similar output to using the run command when you ran all the files together as a whole package. Ex:

./test1

Or whatever your executable filename happens to be called when it was created.

答案6

得分: 7

你可以通过将另一个文件声明为模块来从另一个文件中导入函数。将两个文件都放在同一个项目文件夹中。
第一个文件 test1.go 应该如下所示:

package main

func main() {
    demo()
}

从第二个文件中删除 main 函数,因为一个包中只能存在一个 main 函数。第二个文件 test2.go 应该如下所示:

package main

import "fmt"

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

现在在任何终端中,将项目目录设置为工作目录,运行以下命令:
go mod init myproject
这将在项目目录中创建一个名为 go.mod 的文件。该 mod 文件的内容可能如下所示:

module myproject

go 1.16

现在只需在终端中运行命令 go run .!demo 函数将从第一个文件中执行,如所需的那样!

英文:

You can import functions from another file by declaring the other file as a module. Keep both the files in the same project folder.
The first file test1.go should look like this:

package main

func main() {
	demo()
}

From the second file remove the main function because only one main function can exist in a package. The second file, test2.go should look like below:

package main

import "fmt"

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

Now from any terminal with the project directory set as the working directory run the command:
go mod init myproject.
This would create a file called go.mod in the project directory. The contents of this mod file might look like the below:

module myproject

go 1.16

Now from the terminal simply run the command go run .! The demo function would be executed from the first file as desired !!

答案7

得分: 6

<pre>
<b>文件夹结构</b>

duplicate
|
|--duplicate_main.go
|
|--countLines.go
|
|--abc.txt
</pre>

duplicate_main.go

    package main

    import (
	    "fmt"
	    "os"
    )

    func main() {
	    counts := make(map[string]int)
	    files := os.Args[1:]
	    if len(files) == 0 {
		    countLines(os.Stdin, counts)
	    } else {
		    for _, arg := range files {
			    f, err := os.Open(arg)
			    if err != nil {
				    fmt.Fprintf(os.Stderr, "dup2: %v\n", err)
				    continue
			    }
			    countLines(f, counts)
			    f.Close()
		    }
	    }

	    for line, n := range counts {
		    if n > 1 {
			    fmt.Printf("%d\t%s\n", n, line)
		    }
	    }
    }

countLines.go

    package main

    import (
	    "bufio"
	    "os"
    )

    func countLines(f *os.File, counts map[string]int) {
	    input := bufio.NewScanner(f)
	    for input.Scan() {
		    counts[input.Text()]++
	    }
    }
  1. go run ch1_dup2.go countLines.go abc.txt
  2. go run *.go abc.txt
  3. go build ./
  4. go build ch1_dup2.go countLines.go
  5. go build *.go
    </pre>
英文:

<pre>
<b>Folder Structure</b>

duplicate
|
|--duplicate_main.go
|
|--countLines.go
|
|--abc.txt
</pre>

duplicate_main.go

    package main

    import (
	    &quot;fmt&quot;
	    &quot;os&quot;
    )

    func main() {
	    counts := make(map[string]int)
	    files := os.Args[1:]
	    if len(files) == 0 {
		    countLines(os.Stdin, counts)
	    } else {
		    for _, arg := range files {
			    f, err := os.Open(arg)
			    if err != nil {
				    fmt.Fprintf(os.Stderr, &quot;dup2: %v\n&quot;, err)
				    continue
			    }
			    countLines(f, counts)
			    f.Close()
		    }
	    }

	    for line, n := range counts {
		    if n &gt; 1 {
			    fmt.Printf(&quot;%d\t%s\n&quot;, n, line)
		    }
	    }
    }

countLines.go

    package main

    import (
	    &quot;bufio&quot;
	    &quot;os&quot;
    )

    func countLines(f *os.File, counts map[string]int) {
	    input := bufio.NewScanner(f)
	    for input.Scan() {
		    counts[input.Text()]++
	    }
    }
  1. go run ch1_dup2.go countLines.go abc.txt
  2. go run *.go abc.txt
  3. go build ./
  4. go build ch1_dup2.go countLines.go
  5. go build *.go

答案8

得分: 5

作为一个没有弄清楚Go模块情况的愚蠢人,应该这样说:

  1. 创建你的main.go文件。
  2. 在同一个目录下,在终端中输入以下命令:

go mod init "你的模块名称"

  1. 创建一个新的目录并进入其中。

  2. 创建一个新的.go文件,并将目录的名称作为包名。

  3. 编写任何你想要的函数;只需注意你的函数必须以大写字母开头。

  4. 回到main.go文件中,并导入"你的模块名称/你的新目录的名称"。

  5. 最后你需要做的是在包名后面写上你的函数名:

"你的新目录的名称" + "." + YourFunction()

  1. 在终端中输入以下命令:

go run .

你也可以使用go run main.go
有时候你不想创建一个新的目录,而是想在同一个目录中创建新的.go文件,在这种情况下,你需要注意的是,函数是否以大写字母开头并不重要,你应该运行所有的.go文件:

go run *.go

因为

go run main.go

是无效的。

英文:

as a stupid person who didn't find out what is going on with go module
should say :

  1. create your main.go
  2. in the same directory write this in your terminal

> go mod init "your module name"

  1. create a new directory and go inside it

  2. create a new .go file and write the directory's name as package name

  3. write any function you want ; just notice your function must starts with capital letter

  4. back to main.go and
    > import "your module name / the name of your new directory"

  5. finally what you need is writing the name of package and your function name after it
    > "the name of your new dirctory" + . + YourFunction()

  6. and write this in terminal
    > go run .

you can write go run main.go instead.
sometimes you don't want to create a directory and want to create new .go file in the same directory, in this situation you need to be aware of, it doesn't matter to start your function with capital letter or not and you should run all .go files
> go run *.go

because
> go run main.go

doesn't work.

答案9

得分: 1

首先,在根目录下,你可以运行go mod init mymodule(注意:mymodule只是一个示例名称,你可以根据自己的需要进行更改),然后可能需要运行go mod tidy

文件夹结构将如下所示:

.
├── go.mod
├── calculator
│   └── calculator.go
└── main.go

对于**./calculator/calculator.go**文件:

package calculator

func Sum(a, b int) int {
	return a + b
}

其次,你可以在main.go中导入calculator包,并使用Sum函数(注意函数名首字母大写):

对于**./main.go**文件:

package main

import (
	"fmt"
	"mymodule/calculator"
)

func main() {
	result := calculator.Sum(1, 2)
	fmt.Println(result)
}

之后,你可以在根目录下运行以下命令:

go run main.go

控制台将返回结果3

附加内容:对于./go.mod文件:

module mymodule

go 1.19

注:这是我第一次回答问题,希望对你有所帮助。

英文:

Let me try.

Firstly

at the root directory, you can run go mod init mymodule (note: mymodule is just an example name, changes it to what you use)

and maybe you need to run go mod tidy after that.

Folder structure will be like this

.
├── go.mod
├── calculator
│   └── calculator.go
└── main.go

for ./calculator/calculator.go

package calculator

func Sum(a, b int) int {
	return a + b
}

Secondly

you can import calculator package and used function Sum (note that function will have Capitalize naming) in main.go like this

for ./main.go

package main

import (
	&quot;fmt&quot;
	&quot;mymodule/calculator&quot;
)

func main() {
	result := calculator.Sum(1, 2)
	fmt.Println(result)
}

After that

you can run this command at root directory.

go run main.go

Result will return 3 at console.

Bonus: for ./go.mod

module mymodule

go 1.19

ps. This is my first answer ever. I hope this help.

huangapple
  • 本文由 发表于 2013年1月4日 18:15:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/14155122.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定