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


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


package main

func changeTest(newTest string) {
    test = newTest


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 (

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