Coding in Go Lang
- Create a map:
myMap := make(map[int] int) - check if map contains key:
if val, isPresent := myMap[key]; isPresent { //do something } - Add/Update map
myMap[key] = val - To iterate over a map
for key, val := range myMap { //do something }
-
Create a set:
mySet := make(map[int] bool) -
Check if set contains key:
if val, isPresent := mySet[key]; isPresent { //do something } -
Add value to set
mySet[key] = true
- to create a char/character, rune is the keyword
var myChar rune - To convert rune to string
val := string(myChar) - To convert string to rune
myRune := []rune(myString) - If you want to replace a char at index i in string.
a) Convert it to array of rune
b) update the char at index i
c) Convert the rune array to string (follow #2)
myRune[i] = 'c'
- Find length of string
len(str)
- Substring of string
s[: len(s) - 3]
- To check if 2 strings are equal
if s1 == s2 { // do something } - To remove one or multiple whitespaces from string, use strings.Fields It returns array of string without any whitespaces
words := strings.Fields(str)
- To convert array to string, use strings.Join()
strings.Join(words, " ")
If we are updating strig frequently, a new string will be created in the memory. Reason - strings are immutable in Go, so if we are adding content to it, we are creating a new string every time. Use strings.Builder instead
- To create string builder
var sb strings.Builder - To add string to string builder
sb.WriteString(s) - To convert it to string
sb.String()
- Convert int to string strNum := strconv.Itoa(num)
- Max int value max := math.MaxInt32
- Create a stack array of type rune/char
var stack[] rune - To push to the stack
stack = append(stack, c) - Pop from stack
stack = stack[: len(stack) -1] - Peek from stack
prev := stack[len(stack) -1] - Check stack length
len := len(stack)
- Slice is a variable sized array. We can use it when we don't know the exact size of array we want.
mySlice := make([]int, size) - While passing slice as an argument, we don't need to pass them as pointer. In Go, everything is passed by value, slices too. But a slice variable is a pointer to the value already.
- To check if two slice are equal
reflect.DeepEqual(sl1, sl2)
- To create an array of fixed size
arr := make([]int, 10) - To sort array element
sort.Ints(arr) - To create a 2-D array of nxn
arr := make([][]int, n) - Create an array of nx2
var arr[][2] int - To add value to this array
arr = append(arr, [2]int {i, j}) - To create rxc array
arr := make([][]int, r) for i := range arr { arr[i] = make([]int, c) } - Sort 2-D array
sort.Slice(arr, func (a, b int) bool { return arr[a][0] > arr[b][0] })
for (i := 0; i< len(word); i++) {
// do something
}
or
for index, val := range arr {
// do something
}