Last active
March 20, 2021 09:52
-
-
Save artturijalli/dea26b35a21e3efd294e299fe8cbb248 to your computer and use it in GitHub Desktop.
Basics of Go language.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import "fmt" | |
func main() { | |
fmt.Println("Hello, world!") | |
// Creating variables | |
var x1 int = 5 | |
var y1 int = 10 | |
var sum1 int = x1 + y1 | |
fmt.Println(sum1) | |
// Shorthand for creating variables | |
x2 := 5 | |
y2 := 10 | |
sum2 := x2 + y2 | |
fmt.Println(sum2) | |
// If-else statements | |
number := 9 | |
if number < 10 { | |
fmt.Println("The number is less than 10") | |
} else if number == 10 { | |
fmt.Println("The number is 10") | |
} else { | |
fmt.Println("The number is greater than 10") | |
} | |
// ARRAYS | |
// Initialize an array with three zeros | |
var arr1 [3]int | |
fmt.Println(arr1) // prints [0 0 0] | |
// Use an index to change elements in an array | |
arr1[0] = 10 | |
fmt.Println(arr1) // prints [10 0 0] | |
//A Shorthand for creating arrays | |
arr2 := [3]int{1,2,3} | |
fmt.Println(arr2) // prints [1 2 3] | |
// These arrays are fixed in length. Pretty inconvenient | |
// Let's create an array slice in which you can add elements | |
arr3 := []int{1,2,3} | |
arr3 = append(arr3, 4) | |
fmt.Println(arr3) // prints [1 2 3 4] | |
// DICTIONARIES A.K.A MAPS | |
sides := make(map[string]int) // creates a string: int map | |
// Adding new key-value pairs to the map | |
sides["triangle"] = 3 | |
sides["square"] = 4 | |
sides["pentagon"] = 5 | |
fmt.Println(sides) // prints map[pentagon:5 square:4 triangle:3] | |
delete(sides, "triangle") | |
fmt.Println(sides) // prints map[pentagon:5 square:4] | |
// LOOPS | |
// In Go, there are only for loops | |
// Loop numbers from 0 to 4 and print them | |
for i := 0; i < 5; i++ { | |
fmt.Println(i) | |
} | |
// For loop can be used as a while loop too | |
i := 0 | |
for i < 5 { | |
fmt.Println(i) | |
i++ | |
} | |
// Loop through an array using range | |
numbers := []int{1,2,3} | |
for index, value := range numbers { | |
fmt.Println("Index:", index, "Value:", value) | |
} | |
// Loop through a map using range | |
data := make(map[string]int) // creates a string: int map | |
data["one"] = 1 | |
data["two"] = 2 | |
data["three"] = 3 | |
for key, value := range numbers { | |
fmt.Println("Key:", key, "Value:", value) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment