Concepts for Go
Go, also known as Golang, is a statically typed, compiled programming language developed by Google in 2007. It's designed for simplicity, efficiency, and concurrency. Go's syntax is minimalistic yet expressive, making it easy to read and write. It offers built-in support for concurrency through goroutines and channels, allowing developers to efficiently utilize multicore processors. Go also includes features like garbage collection, type safety, and a rich standard library that simplifies common tasks such as networking, file I/O, and JSON handling. With its focus on performance, scalability, and simplicity, Go is widely used for building web servers, cloud-based applications, and distributed systems.
Print Text
package main import "fmt" func main() { fmt.Println("Hello World!") }
Comments
// one line comment /* multi line comment */
Variables
var carCount int = 2 var name string = "Joe" var isPurple bool = true
Data Types
var carCount int = 2; var age uint8 = 15 var seaLevel int16 = -10000; var usBudget int64 = 11000000000; var lightSpeed uint64 = 11799312874; var myGPA float32 = 3.45; var piValue float64 = 3.14159265; var isMale bool = true; var lastLetter string = "Z"; var myName string = "Joe";
Math Op
var carCount = 6; var truckCount = 3; var total = carCount + truckCount; fmt.Println(total); var subtract = carCount - truckCount; fmt.Println(subtract); var multiple = carCount * truckCount; fmt.Println(multiple); var divisible = carCount / truckCount; fmt.Println(divisible); // performs division and gets remainder which is 0 var modulo = carCount % truckCount; fmt.Println(modulo);
Math Functions
package main import ( "fmt" "math" "math/rand" "time" ) var power = math.pow(3, 6); fmt.Println(power); var root = math.Sqrt(16.0); fmt.Println(root); var floorVal = math.Floor(3.14); fmt.Println(floorVal); var ceilVal = math.Ceil(4.3); fmt.Println(ceilVal); var roundVal = math.Round(3.4); fmt.Println(roundVal); // random number from 0 to 100 rand.Seed(time.Now().UnixNano()); ranNum := rand.Intn(101); fmt.Println(ranNum);
If/Else
import "fmt" var carCount = 6; if carCount > 3 { fmt.Println("More than three cars") } else if (carCount == 3) { fmt.Println("Equal to three cars") } else { fmt.Println("Less than three cars") }
Ternary
// No Native Support or Implementation
Switch
import "fmt" var carCount = 3; switch carCount { case 1: fmt.Println("One car") case 2: fmt.Println("Two cars") case 3: fmt.Println("Three cars") default: fmt.Println("More than three") }
Functions
func handleCars(cars int, wheels int) int { var total int = cars * wheels; return total; } var result int = handleCars(3, 4) fmt.Println(result)
Interpolation
import "fmt" var name = "Joe" var car = "Mazda" var result = fmt.Sprintf("%s drives a %s", name, car) fmt.Println(result)
Type Casting
import ( "fmt" "math" "strconv" ) func squareA(length int) int { var result = int(math.Pow(float64(length), float64(2))); return result } var squareL = "4" convertedVal, err := strconv.Atoi(squareL) if (err != nil) { fmt.Println(err); return; } var area = squareA(convertedVal) fmt.Println(area)
Date and Time
import ( "time" "fmt" ) // current time in milliseconds since 1970 milliTime := time.Now().UnixNano() fmt.Println(milliTime) // current year year := time.Now().Year() fmt.Println(year) // current month month := time.Now().Month() fmt.Println(month) // current day day := time.Now().Day() fmt.Println(day) // current formatted date fullDate := time.Now().Format("01/02/2006") fmt.Println(fullDate)
Classes
import "fmt" type Cars struct { carList []string } func (cars *Cars) addCar(name string) { cars.carList = append(cars.carList, name) } func (cars *Cars) removeFirst() { cars.carList = cars.carList[1:] } func (cars Cars) getFirstVal() string { if(len(cars.carList) > 0) { return cars.carList[0] } return "" } newList := Cars{} newList.addCar("Honda") newList.addCar("Mazda") newList.addCar("Toyota") newList.removeFirst() firstCar := newList.getFirstVal() fmt.Println(firstCar)
Inheritance
// No Native Support or Implementation
Method Overload
// No Native Support or Implementation
Abstract Class
// No Native Support or Implementation
Static Class
// No Native Support or Implementation
Arrays/Lists
package main import "fmt" var names = [...]string{"Joe", "Alex", "Bob"} names[1] = "Tom" var name string = names[1] var numItems int = len(names) fmt.Println(name) fmt.Println(numItems)
Array Methods
cars := []string {"Honda","Mazda","Toyota"} // number of elements fmt.Println(len(cars)) // sliced from index 1 to 2 slicedCars := cars[1: 2] fmt.Println(slicedCars[0]) // adds new element to end cars = append(cars, "Ford") fmt.Println(cars[3]) // removes first element cars = cars[1:]; fmt.Println(cars); // removes last element cars = cars[:len(cars) - 1]; fmt.Println(cars);
Concatenation
import "fmt" // shorthand way to set up arrays carsListKr := []string{"Kia", "Hyundai", "Daewoo"}; carsListJp := []string{"Honda", "Mazda", "Toyota"}; // three dot operator includes entire array combined := append(carsListKr, carsListJp...); fmt.Println(combined[1]); fmt.Println(combined[4])
Sort Method
import ( "sort" "fmt" ) ages := []int{5, 3, 1, 6, 7, 4, 19} sort.Ints(ages) fmt.Println(ages)
Objects
import "fmt" type User struct { first string last string age int retired bool carBrands []string } func (usr User) fullName() string { return fmt.Sprintf("%s %s", usr.first, usr.last) } brands := []string{"Mazda", "Toyota"} user := User { "Joe", "Doe", 23, false, brands } fmt.Println(user.first) fmt.Println(user.carBrands[1]) fmt.Println(user.fullName())
Maps (Key/Value)
import "fmt" carMap := map[string]string{ "Joe": "Toyota", "Bob": "Mazda", "Tom": "Ford" } result := carMap["Tom"] fmt.Println(result) delete(carMap, "Tom") _, found := carMap["Tom"] fmt.Println(found)
Sets
// no built in implementation
Stack
import "fmt" cars := []string{} cars = append(cars, "Mazda") cars = append(cars, "Toyota") cars = append(cars, "Honda") fmt.Println(cars[len(cars) - 1]) cars = cars[:len(cars) - 1] fmt.Println(cars[len(cars) - 1])
Queues
import "fmt" cars := []string{} cars = append(cars, "Mazda") cars = append(cars, "Toyota") cars = append(cars, "Honda") fmt.Println(cars[0]) cars = cars[1:] fmt.Println(cars[0])
Linked List
import "fmt" type Node struct { value string next *Node } type LinkedList struct { head *Node } func (node *LinkedList) addValue(value string) { newNode := &Node {value, nil} if node.head == nil { node.head = newNode } else { current := node.head for current.next != nil { current = current.next } current.next = newNode } } func (node *LinkedList) returnHead()string { return node.head.value } func (node *LinkedList) traverse() { current := node.head for current != nil { fmt.Println(current.value) current = current.next } } carList := LinkedList{} carList.addValue("Mazda") carList.addValue("Toyota") carList.addValue("Honda") fmt.Println(carList.returnHead()) carList.traverse()
Graphs
import "fmt" type Graph struct { graphMap map[string][]string } func (graph *Graph) addNode(value string) { if (graph.graphMap == nil) { // create new hashmap graph.graphMap = make(map[string][]string) } graph.graphMap[value] = []string{} } func (graph *Graph) addVertices( node1 string, node2 string ) { _, n1exists := graph.graphMap[node1] if n1exists == false { graph.graphMap[node1] = []string{} } _, n2exists := graph.graphMap[node1] if n2exists == false{ graph.graphMap[node2] = []string{} } graph.graphMap[node1] = append(graph.graphMap[node1], node2) graph.graphMap[node2] = append(graph.graphMap[node2], node1) } func (graph *Graph) breadthTraverse(start string) { queue := []string{start} visited := map[string]bool{} visited[start] = true for len(queue) > 0 { val := queue[0] fmt.Println(val) queue = queue[1:] var tempArr = graph.graphMap[val] for i := 0; i < len(tempArr); i++ { _, exists := visited[tempArr[i]] if exists == false { queue = append(queue, tempArr[i]) visited[tempArr[i]] = true } } } } func (graph *Graph) depthTraverse(start string) { stack := []string{start} visited := map[string]bool{} visited[start] = true for len(stack) > 0 { val := stack[len(stack) - 1] fmt.Println(val) stack = stack[:len(stack) - 1] var tempArr = graph.graphMap[val] for i := 0; i < len(tempArr); i++ { _, exists := visited[tempArr[i]] if exists == false { stack = append(stack, tempArr[i]) visited[tempArr[i]] = true } } } } newGraph := Graph{} newGraph.addNode("a"); newGraph.addVertices("a", "b"); newGraph.addVertices("a", "c"); newGraph.addVertices("b", "d"); newGraph.addVertices("b", "e"); newGraph.addVertices("d", "f"); newGraph.addVertices("d", "g"); newGraph.addVertices("d", "h"); newGraph.addVertices("e", "i"); newGraph.addVertices("e", "j"); newGraph.breadthTraverse("a"); newGraph.depthTraverse("a");
For Loops
import "fmt" names := []string{"Joe", "Alex", "Bob"}; for i := 0; i < len(names); i++ { fmt.Println(names[i]); }
While Loops
import "fmt" carList := []string{"Mazda", "Toyota", "Honda"} for len(carList) > 0 { fmt.Println(carList[0]) carList = carList[:0] } fmt.Println(len(carList))
Loop Breaks
import "fmt" cars := []string{"Toyota", "Honda", "Mazda"}; for i := 0; i < len(cars); i++ { if (cars[i] == "Honda") { result := fmt.Sprintf("Found at index %d", i) fmt.Println(result) break } result := fmt.Sprintf("Visited index %d", i) fmt.Println(result) }
Recursion
import "fmt" func getSum (arr []int) int { if (len(arr) == 0) { return 0 } firstVal := arr[0] // slice first element arr = arr[1:] fmt.Println(firstVal) fmt.Println(arr) return firstVal + getSum(arr) } testArr := []int{1, 2, 4, 5} sum := getSum(testArr); fmt.Println(sum)
Regex Words
import ( "fmt" "regexp" ) // use back qoutes in pattern pattern := regexp.MustCompile(`\w+`); phrase := "I am legend" result := pattern.FindString(phrase) fmt.Println(result)
Regex Numbers
import ( "fmt" "regexp" ) // use back qoutes in pattern pattern := regexp.MustCompile(`\d+`); phrase := "I am 23" result := pattern.FindString(phrase) fmt.Println(result)
Regex Test
import ( "fmt" "regexp" ) pattern := "Lee" phrase := "Bob Lee" result, _ := regexp.MatchString(pattern, phrase) fmt.Println(result)
Regex Characters
import ( "fmt" "regexp" ) // use back qoutes in pattern pattern := regexp.MustCompile(`#+\w+`); phrase := "##I am legend##" result := pattern.FindString(phrase) fmt.Println(result)