英文:
Using function from `main` package into main.go file
问题
我在根目录下有两个文件:main.go
和utils.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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论