Go Variables: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 50: Line 50:
A "long" declaration statement that is not followed by an explicit initialization implicitly initializes the variable with the [[Go_Language#Zero_Value|zero value]] of the variable's type.  
A "long" declaration statement that is not followed by an explicit initialization implicitly initializes the variable with the [[Go_Language#Zero_Value|zero value]] of the variable's type.  


More variables can be declared at the same time with:
More variables of different types can be declared at the same time with:
<syntaxhighlight lang='go'>
<syntaxhighlight lang='go'>
var (
var (
   a int
   a, b int
   b string
   c string
   ...
   ...
)
)

Revision as of 00:28, 10 July 2024

External

Internal

Overview

Variables are names associated with memory locations that store values. Variable name rules are described in the Naming section. Each variable has a type. Because Go is a statically typed language, the type associate with a variable may not change after the declaration. Each variable defined in Go occupies a unique memory location. It is not possible to have two variables that share the same storage location. It is possible to have two variable that point to the same storage location, in case of pointer variables, but this is not the same thing as sharing the same storage location. In other words, Go has no reference variables.

Naming

The names of variable identifiers in Go follow general naming conventions for identifiers.

Variable names should be short rather than long. The closer to declaration a name is used, the shorter it should be. Conversely, the farther away from the declaration you use it, the longer the name should be. Long variable names obscure what the code does. Longer names may help in long functions, or functions with many local variable, but often this just means you should refactor.

i is fine when iterating over an array, prefer i to index. Prefer r to reader. Prefer b to buffer. Prefer count to runeCount inside a function named RuneCount.

Two letter variable names should be used for slices or maps.

var tt []*Thing // tt is many

When choosing variable names, try to make them work well with their enclosing package name:

Try to Make Package Names and Exported Names Work Together

Go does not have reference variables, but it does have pointers, so one may assume that there are naming conventions to make obvious when a variable contains a pointer, and when it contains a value. In fact, there aren't such conventions. Pointer and value variable names are indistinguishable. For more details, see:

Pointer Variable Naming

(No) Reference Variables

Go does not have reference variables. Each variable defined in Go occupies a unique memory location, which contains the value of the variable. Arrays, slices, maps, channels, etc. variables are all values, not references. As such, there is no pass-by-reference in Go, everything is passed by value. To achieve behavior similar to pass-by-reference, use pointers. This is explained here:

Pass by Value vs. Pass by Reference vs. Pass by Pointer in Go

Variable Declaration and Initialization

In Go variables must be explicitly declared to be used. There is a "long" declaration statement and a "short" declaration statement. The initialization is optional. A variable that is not explicitly initialized, is implicitly initialized with the zero value for the variable's type.

"Long" Declaration

The "long" declaration statement starts with the var keyword, followed by the name and the type of the variable:

var <variable-name>[, <variable-name-2>, ...]  <type>

Examples:

var size int
var size, weight int

Declaration without Initialization

A "long" declaration statement that is not followed by an explicit initialization implicitly initializes the variable with the zero value of the variable's type.

More variables of different types can be declared at the same time with:

var (
  a, b int
  c string
  ...
)

A variable that can take any type can be declared using interface{} or its equivalent any:

var r any

Also see:

Variables, Parameters, Arguments

Variable Initialization after Declaration

var color string
color = "blue"

Variable Initialization in Declaration

Variables can be initialized in the declaration:

var color string = "blue"

This is redundant, and some editors will render the type name in gray and pop up a soft static analysis warning: "Type can be omitted", because an alternative syntax, initialization with type inference is available.

Variable Initialization with Type Inference

var color = "blue"

Swap Variable Values

a, b = b, a

Also works with arrays and slices.

Short Variable Declaration

The declaration and initialization can be performed together with the := operator. This obviates the need for the var keyword and it deploys type inference. This kind of declaration can only be performed inside a function.

color := "blue"

The short variable declaration can be used to initialize more than one variable at the same time, when the assignment contains multiple values, or when on the right side of the assignment there is a function that returns multiple values:

i, j := 0, 1
color, size := someFuncWithTwoReturnValues(...)

Variable Declaration with new()

new() creates a variable or a certain type, specified as the argument of the new() function invocation, and returns a pointer pointer to that variable.

ptri := new(int)
*ptri = 3

Why do we need to involve variables here? There's no variable, new() just allocates space for an instance of a certain type and returns a pointer to it.

Creating instances with New()

Go New()

Scope

The scope of a variable is defined as places in the code where the variable can be accessed. In Go, the scope of a variable can be formally defined by using the concept of block: Go is a lexically scoped language using blocks.

Given two blocks bi and bj, we say that bi ≥ bj if bj is inside (is enclosed in) bi. This relationship is transitive.

The formal definition of visibility (or accessibility) of a variable v is: a variable v is visible in a block bj if it is declared in a block bi so bi ≥ bj.

If a variable with the same name is declared in two blocks between which there is a an inclusion relationship, the variable defined in the "closest" block takes precedence.

Also see:

Environment of a Function

Variable Deallocation

Memory Management and Garbage Collection | Variable Deallocation