Is `func f()` a statement?

The Go FAQ says:

the semicolons … are injected automatically … at the end of any line that could be the end of a statement.

it forces a brace style.
For instance, the opening brace of a function cannot appear on a line by itself.

It seems that Go will recognize func f() as a single statement.


However, when I run the following code:

package main
func f()
func main() { println(f) }

got missing function body.

Is there anything wrong with this? You’re defining a function and missing the body, which is wrong.

var f func()

Do you want to express function variables?

This question is about Go’s automatic semicolon insertion.

The error message indicated Go knows that func f() will followed by a {, so obviously ; shouldn’t be inserted at the end of func f() unless it can be a statement itself.

Exactly. Go knows that func f() is incomplete, and hence it does not recognize it as a statement and does not insert a semicolon.

But the FAQ indicates that a semicolon will be inserted at the end of func f() automatically thus

func f()
{ }

is incorrect.

A missing body is not necessarily wrong.
You can provide the implementation in an asm_*.s file

See https://go.dev/ref/spec#Function_declarations:

A function declaration without type parameters may omit the body. Such a declaration provides the signature for a function implemented outside Go, such as an assembly routine.

1 Like

No, the FAQ states that Go inserts a semicolon if the end of the line could be the end a complete statement. The end of func f() cannot be the end of a complete statement by any definition, so Go does not insert a semicolon and errors out instead.

1 Like

True, but you need to compile this in a special way: go tool compile -S <gofile.go>. See A Quick Guide to Go’s Assembler - The Go Programming Language

1 Like

go tool compile -S <gofile.go> creates assembler from the gofile.go

To implement a function in assembler, it’s enough to have the implementation in asm_amd64.s (name depends on platform) in the directory where you call go build .

My fault. The assembly I used for testing was not correct, hence go build did not work for me.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.