Basics

Updated: April 21, 2020

Learn the basic components that make up the Go language.


Table of Contents

SYNTAX

// This is a single line comment

/* This is
a multi line
comment */

"Double quote strings"
'Go does not allow'

math.Pi		// Name is exported if it is capitalized to be used from an imported package

return		// A return statement without arguments returns the named return values. This is known as a "naked" return. 

TYPES

bool

string

int  int8  int16  int32  int64		// signed intergers can include negative numbers
uint uint8 uint16 uint32 uint64 uintptr		// unsigned integers only contain 0 or positive numbers

byte // alias for uint8

rune // alias for int32 | represents a Unicode code point

float32 float64

complex64 complex128

ERRORS

type error interface {
	Error() string		// has an error method that returns a string
}
var ErrNoName = errors.New("Zero length page name")

func NewPage(name string) (*Page, error)
{
	if len(name) == 0 {
		return nil, ErrNoName
	}
}

CONVERSIONS

The expression T(v) converts the value v to the type T.

Some numeric conversions:

var i int = 42
var f float64 = float64(i)
var u uint = uint(f)

Or, put more simply:

i := 42
f := float64(i)
u := uint(f)

Unlike in C, in Go assignment between items of different type requires an explicit conversion. Try removing the float64 or uint conversions in the example and see what happens.

ZERO VALUES

0 		// for numeric types,
false 	// for the boolean type, and
"" 		// (the empty string) for strings.

SCOPE

VARIABLES

var num_items int = 1000		// var declaration with explicit type

var price1, price2 float64 = 9.99, 8.99		// declare multiple variables of the same type

price1, price2 := 9.99, 8.99		// := called short assignment | implicit var declaration | cannot be used outside a function. Type Inference is when = or := does not explicit type.

---
import "fmt"

var c, python, java bool	// <-- Package level variable

func main() {
	var i int				// <-- Function level variable
	fmt.Println(i, c, python, java)
}
---

CONSTANTS

RANGE

LOOPS

ARRAYS

SWITCHES

SLICES

MAPS

FUNCTIONS

STRUCTS

INTERFACES

METHODS

CALLS

POINTERS

VALUES [#values]

CHANNELS

// Declaring and initializing
c := make(chan int)

// Sending a value on a channel
c <- 1

// Receiving a value from a channel
x = <-c

CONCURRENCY