Non-declaration statement outside function body in Go

You need

var test = "This is a test"

:= only works in functions and the lower case ‘t’ is so that it is only visible to the package (unexported).

A more thorough explanation

test1.go

package main

import "fmt"

// the variable takes the type of the initializer
var test = "testing"

// you could do: 
// var test string = "testing"
// but that is not idiomatic GO

// Both types of instantiation shown above are supported in
// and outside of functions and function receivers

func main() {
    // Inside a function you can declare the type and then assign the value
    var newVal string
    newVal = "Something Else"

    // just infer the type
    str := "Type can be inferred"

    // To change the value of package level variables
    fmt.Println(test)
    changeTest(newVal)
    fmt.Println(test)
    changeTest(str)
    fmt.Println(test)
}

test2.go

package main

func changeTest(newTest string) {
    test = newTest
}

output

testing
Something Else
Type can be inferred

Alternatively, for more complex package initializations or to set up whatever state is required by the package GO provides an init function.

package main

import (
    "fmt"
)

var test map[string]int

func init() {
    test = make(map[string]int)
    test["foo"] = 0
    test["bar"] = 1
}

func main() {
    fmt.Println(test) // prints map[foo:0 bar:1]
}

Init will be called before main is run.

Leave a Comment