将`main`包中的函数用于`main.go`文件中。

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

Using function from `main` package into main.go file

问题

我在根目录下有两个文件:main.goutils.go

main.go文件内容如下:

package main

func main() {
   CustomPrint()
}

utils.go文件内容如下:

package main

import "fmt"

func CustomPrint() {
   fmt.Println("example")
}

然而,我遇到了一个错误,因为customPrint没有被识别。

有没有办法在不创建另一个包来存储utils.go文件的情况下解决这个问题?

英文:

I have 2 files into the root directory: main.go and utils.go.

main.go file is:

package main

func main() {
   CustomPrint()
}

utils.go file:

package main

import "fmt"

func CustomPrint() {
   fmt.Println("example")
}

However, I get an error because customPrint is not recognized.

Is there any way to do that without create another package to store utils.go file?

答案1

得分: 1

其实很简单,当你尝试运行"go run main.go"时,你只执行了main.go文件,而utils.go文件并没有与之一起执行。

首先,你可以只执行

go run

它会提示你错误信息。

如你所见,它期望的是文件列表和多个文件,而不是单个文件,所以会显示"No go files listed"

解决方法是你只需要同时执行这两个文件

go run main.go utils.go

问题就解决了!

它会按照你的期望行为执行。

第二个选项更简单,你不需要输入那么多文件名。

你可以运行

go run ./

它会执行当前目录下的所有.go文件。

英文:

It's Simple actually, When you try to run "go run main.go", You only execute the main.go file. Utils.go file is not executed together with it.

First you can just execute

go run

it will prompt you error.

As you can see that is expect list and multiple files instead of single file, "No go files listed"

The solution is you just need to execute both files

go run main.go utils.go

There you go problem solved!

it will behave as you expected.

Second option is simpler which you do not have to type so many files.

You can run

go run ./

it will executed every .go files in your current directory

huangapple
  • 本文由 发表于 2022年1月12日 16:48:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/70678600.html
匿名

发表评论

匿名网友

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

确定