Go Concepts - Lexical Structure

From NovaOrdis Knowledge Base
Jump to navigation Jump to search

Internal

Source Files

Go code goes into source files. They have the .go extension.

Each source file is mandatory declared to belong to a package.

They can then optionally import code from other packages, using the import keyword.

Each source file has its own file block.

Thera are no restrictions on the file name, it is not required to have any relationship with the name of the package it contains code for.

Comments

// to the end of the line
/*
  Multiline
  line 1
  ...
  line n
*/

Whitespace

Whitespace in Go are carriage returns (u+000D), newlines (u+000A), spaces (u+0020) and tabs (u+0009).

Semicolons

Go programs may omit most of the semicolons at the end of line if the following conditions apply:

  1. When the input is broken into tokens, a semicolon is automatically inserted into the token stream immediately after a line's final token if that token is:
    1. an identifier
    2. an integer, floating-point, imaginary, rune, or string literal
    3. one of the keywords break, continue, fall through, or return
    4. one of the operators and delimiters ++, --, ), ], or }
  2. To allow complex statements to occupy a single line, a semicolon may be omitted before a closing ")" or "}".

For more details, see the specification:

https://golang.org/ref/spec#Semicolons

Blocks

A block is a sequence of declarations and statements within matching curly braces. The block may be empty. The most common blocks are those defined in the source code - they define block lexical scopes (see variable scopes). Aside from those, Go recognizes the following implicit blocks:

  • The universe block which contains all Go source text.
  • The package block.
  • The file block that contains all the source text in the file.
  • Each if, for and switch statements is considered to be in its own implicit block.
  • Each clause in a switch and select statements acts as an implicit block.

Identifiers

Identifiers name program entities, such as constants, variables, types, functions, packages, etc. An identifier is a sequence of one more letter and digits. The first character must be a letter. The letters are unicode letters or underscore "_". It must not be a keyword, keywords are reserved by the language.

Identifiers can be exported, and the way the first letter is capitalized is relevant to whether the identifier is exported or not. See exported identifiers.

It is idiomatic to use camel case style for Go identifiers.

Pre-Declared Identifiers

Pre-declared identifiers are available by default, without needing to import anything. They are implicitly declared in the universe block.

Pre-declared types: bool, byte, complex64, complex128, float32, float64, int, int8, int16, int32, int64, rune, string, uint, uint8, uint16, uint32, uint64, uintptr and error.

Pre-declared constants: true, false, iota.

Pre-declared functions: append, cap, close, complex, copy, delete, imag, len, make, new, panic, print, println, real, recover. Also see built-in functions.

Pre-declared zero value: nil.

The Blank Identifier

"_" is the blank identifier. The blank identifier is used to tell the compiler that we don't need the variable.

Exported Identifiers

Exported Identifiers

Keywords

The language had reserves a set of keywords that cannot be used as identifiers.

https://golang.org/ref/spec#Keywords
break default func interface select
case defer go map struct
chan else goto package switch
const fallthrough if range type
continue for import return var

Literals

A literal is a notation for representing a fixed value in source code. Go provides literals for booleans, integers, floating-point values, strings, built-in types such as arrays, slices and maps, user-defined types (structs), functions, etc. The compiler is always able to infer the literal's type.

Declarations

A declaration binds an identifier to a constant, type, variable, function, label or package. Every identifier in the program must be declared. No identifier may be declared twice in the same block, and no identifier may be declared in both the file and package block.

Variables

A variable is a storage location in memory. Go being a statically typed language, a variable always has a specific type. A variable also has a name, which is referred to as variable identifier.

The Go compiler will generate an error if a variable is declared and not used.

Variable Declarations

Long Variable Declaration

var <variable_identifier> <variable_type_literal> = <initial_value_literal>

Example:

var a string = "blue"
var b = "red"
var c string
var f = func (i int) int {
        return i
}

Declaring the type is optional if an initial value is specified, the compiler is able to infer the type of the literal, and the variable will be built to have that type.

Assigning a value is optional, if no value is explicitly assigned, the variable is initialized to the type's zero value. However, the type must be specified in this case.

Short Variable Declaration

Another form of variable declaration that always assigns an initial value and also infers the variable type based on the literal type is the following:

<variable_identifier> := <initial_value_literal>

Example:

a := "blah"

This syntax can be used in a for loop. Note that this form cannot be used for the declaration of a package-level variable.

Generally, the shorter value should be used whenever possible. Some books claim that the long value is not "idiomatic". For more details on variable names, see identifiers.

Multiple variables are declared as such:

var (
     a = 1
     b = 2
     c = "something"
)

Variable Scopes

The range of places where a variable is visible from it is called the scope of the variable.

Go is lexically scoped using blocks.

A variable is visible within the block delimited by the nearest curly braces {}, but not outside them. The variable is visible inside any sub-blocks.

If a variable with the same name is defined in a sub-block, the that variable takes precedence, in the sub-block and its sub-blocks, over the variable declared in the upper block.

Package-Level Variable

An unexported variable declared at the package level (outside any function) is visible throughout the package.

An exported variable declared at the package level is visible throughout the package and in all packages that import the exporting package.

Functions and Variable Scopes

Functions and Variable Scopes

Pass by Value vs Pass by Reference

Pass by value vs. pass by reference

Pointers

A pointer is a pointer type variable. It contains an address to a memory location. Pointers are not commonly used with built-in types, but are very useful when paired with structs.

In absence of explicit initialization, pointer are initialized to nil.

Reference and Dereference Operators

& the reference operator - returns a pointer type instance which contains the address in memory for the value of the given variable. & should be read as "address of ..."

* the dereference operator - gives access to the value at the memory location indicated by the pointer contained by the given variable. The variable must contain a pointer type instance, otherwise the compiler will complain. The value thus exposed can be read or written.

var i 
var ptri *int

// pointer to the memory location containing i
ptri = &i

// value the pointer is pointing to
var j = *ptri

// i == j

Constants

Constants are variables whose values cannot be changed once declared. The compiler detects modification attempts and throws a compilation error.

Constant Declarations

The declaration syntax is similar to that used to declare variables:

const <constant_identifier> <constant_type_literal> = <initial_value_literal>

Example:

const a string = "something"
const b = 1

As with variables, the type can be omitted, as it can be inferred.

Multiple constants are declared as such:

const (
     a = 1
     b = 2
     c = "something"
)

Statements

Statements control execution flow within a function.

for

if

Expressions

Operators combine operands into expressions.

Types

The Type System

Functions

Functions

Operators

Operators