= vs :=

Posted

This post will briefly describe the differences between the assignments and short variable declarations in Go. It assumes that you have completed A Tour of Go and have consulted relevant sections of Effective Go and the target audience is primarily newcomers to the Go programming language.

The assignment operator (=) is used to perform assignments (i.e. to assign or reassign values to already declared variables).

The short declaration operator (:=), on the other hand, is used to perform short variable declarations), which are shorthand for regular variable declarations but without a specified type.

Here are four different ways to create a variable with static type int and value 10, each of which are equivalent:

var a int = 10

var b = 10

var c int
c = 10

d := 10

Unlike regular variable declarations, a short variable declaration may redeclare variables in multi-value assignments, assuming at least one variable is new and the redeclared variable is assigned a value of the same type. You’ll see this property used frequently when dealing with errors, as it avoids the need to declare differently named variables such as err1, err2, etc. in the same block of code. For example, consider the CopyFunc function below, which opens two files and copies the contents of one file to the other:

func CopyFile(dstName, srcName string) (written int64, err error) {
    // 'err' is declared for the first time.
    src, err := os.Open(srcName)
    if err != nil {
        return
    }
    defer src.Close()

    // 'err' is redeclared (no need to declare a new variable
    // for the returned error).
    dst, err := os.Create(dstName)
    if err != nil {
        return
    }
    defer dst.Close()

    return io.Copy(dst, src)
}

In general, short variable declarations should be preferred because they are more concise than regular variable declarations/assignments. Note, however, that short variable declarations can only be used inside of functions/methods (declaring global variables at the package level can only be done using a regular variable declaration: var name type = value).

+1 this blog!

Go Design Patterns is a website for developers who wish to better understand the Go programming language. The tutorials here emphasize proper code design and project maintainability.

Find a typo?

Submit a pull request! The code powering this site is open-source and available on GitHub. Corrections are appreciated and encouraged! Click here for instructions.