Understand compile error #2

  1 package main
  2
  3 import "fmt"
  4
  5 const p string = "Death & Taxes"
  6 var q int =  42
  7 const r = 98
  8
  9 // Compile errors
 10 // --------------
 11 //const q := 42
 12 // q := 42
 13
 14 func main() {
 15    fmt.Println("Printing const p - package level scope ", p)
 16    fmt.Println("Printing q - package level scope ", q)
 17    fmt.Println("Printing const r - package level scope ", r)
 18 }

Uncommenting line #11, the error is -

$ go build 2.go

command-line-arguments

.\2.go:11: missing value in const declaration
.\2.go:11: syntax error: unexpected := after top level declaration

Uncommenting line #12, the error is -

$ go build 2.go

command-line-arguments

.\2.go:12: syntax error: non-declaration statement outside function body

Does the above error mean that ‘:=’ can only be used inside a function body to assign values to variables ?

Constant declaration writes const q = 42 (without : )
In that case the var statement must be removed or a redeclaration occurs.
The assignment of a new value to a declared variable can only occur inside a func body.
So
var q int = 42

func main() {
q := 42

is legit. See specifications for details https://golang.org/ref/spec#Constants and
you can give a try to the Go lang tour if not done. https://tour.golang.org/welcome/1

1 Like

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