# 27 - ЕЖЕДНЕВНАЯ ПОЧТА

Памятка по синтаксису Golang

Создать переменные

# Create a new zero variable
var a int
# Create a new variable with value
var b = 1.1
# Another way to create new variable with value
c := "string"
# Create a constants
const c = "const string"

Присвоение и сравнения

# Assign value (to created variables)
a = 1
b = 2
# Comparisions
aEqualsB := (a == b)
var aNotEqualsB = (a != b)
aGreaterThanB := (a > b)
var aLessThanB = (a < b)
aGreaterThanOrEqualsB := (a >= b)
var aLessThanOrEqualsB = (a <= b)

Заявления о состоянии

if a == b {
   # Normal if
}
else {
   # There's only one else per if, there's no else-if
}
if a := 1; a == b {
   # If with a new variable
}
# To achieve if-elseif-elseif-...-else, use switch
switch {
case a == b:
   # First if
case a < b:
   # An else-if
case a > b:
   # Another else-if
default:
   # Else
# Usual switch case
switch i {
case 1:
   # There no break in go-switch, every case automatically breaks
case 2, 3:
   # Case of multiple values
default:
   # Otherwise
}

Петли

for i := 1; i < 10; i++ {
   # Basic for with initialization, condition and step
}
for stillTrue {
   # Do-while pattern
}
for {
   # Endless-loop pattern
   # Use break to break loop dynamically
   break
}

Функции

func voidReturnFunction(arg1 int, arg2 string) {
}
func usualFunction(arg int) int {
    return 1
}
func returnMultipleValuesFunction() (int, string) {
    return 1, "string"
}
func varadicFunction(args... int) int {
    return args[0]
}

Массивы

# Create a fixed-size array
var a [5]int
# Create a slice (dynamic-size array)
b := make([]int, 5)
# Access array/slice values
fmt.Print(a[0], a[1])
# Assign array/slice values
a[0] = 0
a[1] = 1
# Create a slice from an array or another slice
c := a[0:2] # c is a slice of a from 0th to 2nd (exclusive)
d := b[:5] # d is a slice of b from 0th to 5th (exclusive)

Карты (хеш-таблицы / словари)

# Create a map of string keys and int values
a := make(map[string]int)
# Access map value by key
fmt.Print(a["key"], a["other key"])
# Assign map value by key
a["key"] = 1
# Check whether key exists
if val, exists := a["key"]; exists {
}

Структуры и указатели

# Declare a struct
type A struct {
    AnAttr      int
    AnotherAttr string
}
# Create a instance of struct
a := A{1, "string"}
# Access struct attributes
a.AnAttr = 2
fmt.Print(a.AnotherAttr)
# Get struct value pointer
b := &a
b.AnotherAttr = "other" # This also change value of a.AnotherAttr
# Create a new struct pointer
c := &A{1, "string"}
# Define a struct function
func (a A) someFunction() {
    a.AnAttr = 1 # Change will not be reflected in receiver
}
# Define a struct pointer function
func (a *A) someFunction() {
    a.AnAttr = 1 # Change will be reflected in receiver
}