gpt4 book ai didi

GoLang gofmt 命令

转载 作者:IT王子 更新时间:2023-10-29 01:49:15 25 4
gpt4 key购买 nike

gofmt 命令不格式化花括号 ({})。

代码:

package main

import "fmt"

func main()
{
fmt.Printf("Hello, world\n")
}

gofmt hello.go 的输出

hello.go:6:1: 预期声明,找到“{”退出状态2

如果我把空格放在任何地方,它就会正确格式化。gofmt 不会格式化大括号吗?

最佳答案

你必须把花括号放在函数声明的同一行,否则你的代码将因为这个语法错误而无法编译

Why are there braces but no semicolons? And why can't I put the opening brace on the next line?

Go uses brace brackets for statement grouping, a syntax familiar toprogrammers who have worked with any language in the C family.Semicolons, however, are for parsers, not for people, and we wanted toeliminate them as much as possible. To achieve this goal, Go borrows atrick from BCPL: the semicolons that separate statements are in theformal grammar but are injected automatically, without lookahead, bythe lexer at the end of any line that could be the end of a statement.This works very well in practice but has the effect that it forces abrace style. For instance, the opening brace of a function cannotappear on a line by itself.

https://golang.org/doc/faq#semicolons

关于GoLang gofmt 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38520011/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com