Defining variables

Using the var keyword, you can define a variable in Go. The syntax is as follows:

var x int
var name string
const pi = 3.14


Data types come after the variable identifer and are mandatory in this form.

Variables value is nil by default.

Constants can only be bool, string or numbers. Always need a value.

In Go constants are true constants and not immutable variables—unlike in Python, JavaScript and others. This means less runtime overhead.



Generally, you can expect Go to infer the type of a variable based on the value you assign to it.












var z int = 42

var text string
text = "Hello!"

lastName := "Doe"


Variables can be created with initialization.

Strings use double quotes.

Initialization shortcut. Only valid inside functions.



Backticks ` are used for raw string literals.












TRY IT OUT

Rob Pike












Question: When might we want to specify a type for numbers?












Scope

Variables are scoped to the block in which they are declared.

package main

// global-scoped (within package) variables
...

func main() {
    // function-scoped variables
    ...
    {
        // block-scoped variables
    }
}