问题没有显示在我的问题选项卡上,但是当我尝试运行它时出现了恐慌。

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

The problem didnt show up on my Problem tab, but there is panic when i am trying to run it

问题

我创建了3个Go文件,每个文件都使用了相同的包,即package main。它们的目录结构如下:

mydir/
-client.go 
-room.go
-main.go

在我的终端中,没有出现任何问题。但是当我尝试运行/构建main.go时,它返回了一个panic错误:

undefined: newRoom

以下是引发panic错误的代码片段:

// main.go
r := newRoom()

// room.go
func newRoom() *room {
   return &room{}
}

当我尝试删除该函数时,Visual Code会返回一个"Undeclared"错误。当我再次添加该函数时,问题消失了,但是当我尝试运行或构建时,它会返回一个错误,指出newRoom函数未定义。有人知道出了什么问题吗?

最好附带一些解释,说明为什么它不会出现在Visual Code的问题输出中。

英文:

I make 3 go files with each of them is using the same package, which was package main.
It will look like this...

mydir/
-client.go 
-room.go
-main.go

In my terminal, there is no problem that appears on it, but when I try to run/build main.go, it's returning a panic:

undefined: newRoom

here was my snippet code which has panic :

//main.go
r := newRoom()

//room.go
func newRoom() *room{
   return &room{}
}

When I try to delete the function, it's returning an error "Undeclared" in Visual Code. When adding it again, the problem disappears but when I try to run or build it, it returns an error if my newRoom function is undefined. Does anybody have a clue, what's wrong with it?

It's better if answered with some explanation why it doesn't appear on Visual Code Problems output.

答案1

得分: 5

当你尝试构建main.go时,编译器只能看到main.go文件,所以会显示错误信息"undefined new room"。如果你的目录中有多个go文件在第一层级,你应该使用go build .而不是go build main.go

英文:

When you try to build main.go the compiler can see only the main.go file that why error was shown like "undefined new room"
you should use go build . instead of go build main.go if you have multiple go file in first level of your directory.

答案2

得分: 3

以下是从一个包含许多文件的目录中构建二进制文件的命令:

go build ./mydir/...

这个命令会构建mydir文件夹中的包以及所有递归下去的包。运行go help build可以获取更多关于build命令的信息。

你的代码没有任何问题。

英文:

Here is the command to build a binary from a directory with a bunch of files:

go build ./mydir/...

This command build the package in the mydir folder and all packages recursing down. Run go help build to get more about build command.

There is no any issue with your code.

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

发表评论

匿名网友

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

确定