go hello world示例导致未知指令。

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

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, not function.
  • 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

huangapple
  • 本文由 发表于 2021年12月4日 22:12:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/70226373.html
匿名

发表评论

匿名网友

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

确定