Home > Blockchain >  Why can a multiline comment appear between "import" and ImportSpec, but not between Packag
Why can a multiline comment appear between "import" and ImportSpec, but not between Packag

Time:07-08

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.

CodePudding user response:

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
  • Related