iBug
iBug

Reputation: 37287

Why can a multiline comment appear between "import" and ImportSpec, but not between PackageName and ImportPath?

This is the Go spec for an import declaration:

ImportDecl       = "import" ( ImportSpec | "(" { ImportSpec ";" } ")" ) .
ImportSpec       = [ "." | PackageName ] ImportPath .
ImportPath       = string_lit .

The following code compiles:

import /*
 */f "fmt"

But not this code:

import /*
 */f/*
 */"fmt"

Even more strangely, this code compiles:

import /*
 */f /* */ "fmt"

I could not understand the difference between these comment blocks among the tokens.

Upvotes: 3

Views: 109

Answers (1)

rocka2q
rocka2q

Reputation: 2804

The Go Programming Language Specification

Comments

General comments start with the character sequence /* and stop with the first subsequent character sequence */.

A general comment containing no newlines acts like a space. Any other comment acts like a newline.

package main

import /*
 */f/*
 */"fmt"

func main() {
    fmt.Println()
}

https://go.dev/play/p/nxvIDWkWf_q

prog.go:4:5: expected 'STRING', found newline

Upvotes: 1

Related Questions