英文:
go hello world example results in unknown directive
问题
我正在使用macOS Monterey 12.0.1。
我按照这里的描述安装了Go语言:
https://go.dev/doc/tutorial/getting-started
我使用以下命令初始化了模块目录:
~/projects/go
命令如下:
go mod init example/hello
我创建了一个包含以下内容的hello world文件:
package main
import (
"fmt"
)
func main() {
fmt.Println("Hello, world!")
}
然后我在
~/projects/go
目录中运行了以下命令:
go run .
但是我得到了以下错误信息:
[home]/projects/go/go.mod:1: 未知指令: package
[home]/projects/go/go.mod:3: 未知指令: import
[home]/projects/go/go.mod:5: 未知指令: function
[home]/projects/go/go.mod:6:3: 未知指令: fmt.Println
[home]/projects/go/go.mod:7: 未知指令: }
我知道我一定在某个地方犯了一个不可原谅的错误,但我无法找出我偏离正道的地方。
英文:
I am using macos Monterey 12.0.1
I've installed go as described here:
https://go.dev/doc/tutorial/getting-started
I've initialized the module directory
~/projects/go
with
go mod init example/hello
I've created the hello world file with the content:
package main
import {
"fmt"
}
function main() {
fmt.Println("Hello, world!")
}
Then I do
go run .
in the
~/projects/go
directory.
And I am getting:
[home]/projects/go/go.mod:1: unknown directive: package
[home]/projects/go/go.mod:3: unknown directive: import
[home]/projects/go/go.mod:5: unknown directive: function
[home]/projects/go/go.mod:6:3: unknown directive: fmt.Println
[home]/projects/go/go.mod:7: unknown directive: }
I know, I must have committed some unexcusable mistake somewhere but I can't figure out, where I've gone astray.
答案1
得分: 3
你在Go语言中使用func
来定义函数,而不是function
。
而对于导入语句,你应该使用普通的圆括号,而不是花括号。
你的代码的修正版本如下:
package main
import (
"fmt"
)
func main() {
fmt.Println("Hello, world!")
}
请参考这里:https://go.dev/play/p/AH8TPSfGkFd
英文:
- You define functions with
func
in go, notfunction
. - And for imports you should use regular brackets, not curly ones.
The corrected version of your code is like this:
package main
import (
"fmt"
)
func main() {
fmt.Println("Hello, world!")
}
See here: https://go.dev/play/p/AH8TPSfGkFd
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论