Skip to content

Instantly share code, notes, and snippets.

@pszalawinski
Last active January 17, 2021 11:06
Show Gist options
  • Save pszalawinski/bb674bd30d15cb75df9d540e36e8837f to your computer and use it in GitHub Desktop.
Save pszalawinski/bb674bd30d15cb75df9d540e36e8837f to your computer and use it in GitHub Desktop.
Go basics
PROGRAM LAYOUT:
package main
import ( ..) -> import of libs
const ...
var ...
func init(){} -> function which be intilized before executing main program
func main(){} -> main program
1. Declaration of variable
var foo int
var foo int = 12
foo := 12 (compiler knows what kind of variable this is, if there will be 12.5 it uses float64 )
shadowing of variable - if var is declared outside of the package and we have the same variable in the method then compiler will takie this what is in the method
lower case first letter - only in the package
upper case first letter - for export
convertion types:
if variable is in the same scope we can cast to type -> destinationType(var)\
converting strings package - "strconv"
2. Variables
boolean - > bool
when we intilize but not declare variable is always 0
var foo int -> default int = 0
var foo bool -> default 0 so it is false
math operations
a := 8 // 2^3
a << 3 // 2^3 (adding index ) 2^6
a >> 3 // 2^3 - ^3 = 2^0 (removing index)
s = "this is string"
fmt.Printf("%v, %T", s ,s ) -> this is string, string
fmt.Printf("%v, %T", s[2] ,s[2] ) -> 105, uint8 -> this will print the uint for the letter "i" from given string
fmt.Printf("%v, %T", string(s[2]) ,s[2] ) -> i, uint8
runes
var i rune -> chars in go?
CONST
if I want to have const not variable (object which will not change)
const foo int = 42
but we can shadowing constans
i can add cons to var if both are the same type
IOTA
iota is build in counter
a = iota //0
b = iota //1
c = iota //2
const (
isAdmin = 1 << iota
isUser
isHeadquarters
canSeeFinances
canSeeEurope
canSeeAfrica
)
func main() {
var roles byte = isUser | canSeeAfrica | canSeeFinances
fmt.Printf("Is Admin ? %v\n", isAdmin&roles == isAdmin) -> Is admin? false
fmt.Printf("Is User ? %v\n", isUser&roles == isUser) -> Is user? true
}
3. ARRAYS and SLICES
arrays are collections of items of the same type
initinalization of array:
nameOfArray := [3]int{1,2,3}
length of array
len(nameOfArray)
slice is kind of array but have only brackets
a := []int{1,2,3,4,5,6,7,8,9,10}
//(below works also for slices and arrays)
b :=a[:] //slice of all elements
b :=a[3:] //slice from 4th element to end
b :=a[:6] //slice first 6 elements
b :=a[3:5] //slice only 4th and 5th element
creating
a: = make([]int, 3, 100) //creating a slice of integers with three zeros and 100 capacity places
a: = []int{} // creates a slice of ints and 0 len and 0 cap
a = append(a,1)
cutting the middle number:
a := []int{1, 2, 3, 4, 5, 6, 7}
var first int = len(a) / 2
var second int = (len(a) / 2) + 1
b := append(a[:first], a[second:]...)
fmt.Println(b)
//!!! remember that when we will print next time the a slice number of numbers will return but it will be:
print of b -> [1 2 3 5 6 7]
print of a -> [1 2 3 5 6 7 7]
copies refer to same underlying array!
4. MAPS and STRUCTS
creaate a map:
map[key]value
for example:
mapOfCities = map[string]int{
"warszawa":1,
"piaseczno":2,
"poznan":3,
}
operators on map
adding : mapOfCities["szczecin"] = 4
deleting: delete(mapOfCities, "szczecin")
Struct - creates objects
type Dog struct {
name string
age int
companions []string
toys int
}
func main() {
Laos := Dog{
name: "Laos",
age: 4,
toys: 3,
companions: []string{
"Toska",
"Ponek",
},
}
}
Embedding (~Inheritance) of Struct
!! this example shows that DOG is not ANIMAL. DOG has fields like Animal, embeds this.
type Animal struct {
name string
age int
}
type Dog struct {
Animal
companions []string
toys int
}
func main() {
Laos := Dog{}
Laos.name = "Laos"
Laos.age = 4
Laos.toys = 3
Laos.companions = []string{
"Tosia",
"Zosia",
}
}
5. FUNCTIONS
func main() {
i := 200
j := 102
returning(i, j)
}
func returnTrue() bool {
fmt.Println("returning TRUE")
return true
}
func returnFalse() bool {
fmt.Println("returning FALSE")
return false
}
func returning(first int, second int) {
checkbool := checking(first, second)
if checkbool {
if first > second {
returnTrue()
} else {
returnFalse()
}
}
}
func checking(checkOne int, checkTwo int) bool {
if checkOne < 100 || checkTwo < 100 {
fmt.Printf("one of numbers are below 100:\n first number: %v\n second number: %v\n", checkOne, checkTwo)
return false
} else {
return true
}
}
6. SWITCH
switch 1 {
case 1:
fmt.Println("one")
case 2:
fmt.Println("two")
default:
fmt.Println("default")
}
but it can be without tag:
i := 1
switch{
case i <= 1:
fmt.Println("one")
fallthrough -> !! from default switch statement has break after each case, but when i want to pass next need to add fallthrough, but this will override the statement it will bexecuted without checking
case i <= 2:
fmt.Println("two")
default:
fmt.Println("default")
}
7. LOOPS
works the same as others but we can label the loops (label Loop in ex):
Loop:
for ii :=1; i<=3; i++ {
for j := 1, j<=3, j++ {
fmt.Println(i*j)
if i*j >= 3 {
break Loop
}
}
}
loop with j and i will break after the if inside the j loop
looping over collections:
- arrays, slices, maps, strings, channels
for k, v := range collection {}
8. DEFER
defer -> makes that function wth keyword is exeuted last but the execution in that function is taken.
works in LIFO - last in first out
func main() {
start
defer middle
end
}
console:
start
end
middle
9. PANIC
this is sth like excpetion but it ends executing the code
panic happens afeter DEFER so if we will have implemented closing some buffer etc. it will close and then program will panic
way to handle the error and go from panic:
fmt.Println("about to panic")
defer func() { //-> startin an anonymus funtion
if err := recover(); err != nil{
log.Println("Error", err)
}
}() // -> need to add brackets becouse this function need to be invoked
10. POINTER
*int - point to integer
complex types like structs are automatically deferenced (so it needs no asterisk)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment