| Fact | Module | Remarks |
|---|---|---|
| In Go's philosophy, it is better to avoid unnecessary branches and indentation of code. | General | |
| Semicolon is not needed at the end of the code statement. | General | |
| Variable names are case-sensitive. - If a variable starts with an uppercase letter, then that variable is accessible outside the package it was declared in (or exported). - If a variable starts with a lowercase letter, then it is only available within the package it is declared in. |
General | Conventional style of variable names is MixedCaps or mixedCaps (instead of underscore or space). |
| ⭐ Use shorter variable names as possible. | General - Hint | prefer i over index as it is shorter |
| ⭐ Don't use Math functions since those work on float only & typecasting would be needed. | General - Hint | |
| Return variables (1 or multiple) would be defined at the end of function declaration. | Function Declaration | |
Brackets are not needed in for or if constructs. |
Condition Declaration | |
⭐ Initialisation can be skipped with := declare-and-initialize construct.- nil can’t be initialised to the variable without explicit type (var =).- Note := doesn't work with the global variables. |
Variable Declaration/Initialization | i := 72 |
| Type is defined at the end of declaration. | Variable Declaration/Initialization | |
Multiple variables can be assigned by , |
Variable Declaration/Initialization | j, k, l := "shark", 2.05, 15 |
| Trailing comma is not needed while initializing struct. | Struct Initialization | |
| Global Variables initialization | Global Variables Initialization | var g int = 20 |
| ⭐ String is immutable in Go, while slices are mutable. | General | |
| ⭐ Maps & Slices are passed as reference in function in golang | General | Hence appending an element to the slice, will not reflect in the caller function. Either pointer needs to be used or new slice would have to be returned. - sorted := strs (sorted slice would also change as strs is changed) |
| ⭐ In order to modify slice, we should use slice index, instead of range variable | General | |
| ⭐ append() handles nil slices safely | General | In if _, ok := m[key]; ok{m[v] = append(m[v], strs[i])} else {m[v] = []string{strs[i]} } code, if branch is not necessary |
| Purpose | Data Structure | Example |
|---|---|---|
| ⭐ Append element to the list | Array, Slice | output := []int{10} output = append(output, 5) // append 5 to output slice |
| ⭐ Append multiple elements to the list | Array, Slice | output = append(output, input[:5]...) // input[startIndexIncluding : upToNotIncluding] |
| ⭐ Get elements from start to end index from slice | Array, Slice | output[:5] // 0th to 5th index output[1:] // 1st to last index output[1:5] // 1st to 4th index |
| ⭐ Length of an array or slice | Array, Slice | len(array) |
| ⭐ Sort an array or slice | Array, Slice | sort.Ints(seats) |
| ⭐ Sort 2D array or slice | Array, Slice | sort.SliceStable(slice2D, func(i, j int) bool { return slice2D[i][0] < slice2D[j][0] }) |
| ⭐ Refer element in pointer array/slice | Array, Slice | (*out)[0] |
| ⭐ De-referencing 2D array pointer | Array, Slice | out *[][]int |
| ⭐ Create a Map object | Hash Map | m := make(map[int]int) |
| ⭐ Get value from Map | Hash Map | val, ok := m[key] |
| ⭐ Create a set | Hash Set | m := make(map[int]struct{}) |
| ⭐ Create an object of the struct | Struct | obj := new(ListNode) // pointer to object, without all variables initialized obj := ListNode{5, 10} // pointer to object, with all variables of struct initialized |
| ⭐ Declare & Initialize Empty Slice | Slice | slice := []int{} var slice []int |
| ⭐ Declare & Initialize Slice with fixed length | Slice | slice := make([]int, 20) |
| Declare & Initialize Slice with max length | Slice | slice := make([]int, 0, 20) |
| Copy one slice to another | Slice | copy(dest, src) |
| Compare two bytes array | Slice | bytes.Compare(sl1, sl2) |
| Check if two bytes are equal or not | Slice | bytes.Equal([]byte{grid[x-1][y]}, []byte{'1'}) |
| Use slice as stack | Slice | stack := []string{} stack = append(stack, dir) // push stack = stack[:len(stack)-1] // pop |
| ⭐ While loop in GoLang | Loops | for n!=0 {} |
| Convert string to an array of Rune, helps in modifying string | Rune | r := []rune("string") r[0] // rune at 0th index in stringVar |
| Convert rune (i.e. stringArray[i]) to string | Rune | string(x) |
| ⭐ Construct a new string | Rune | r := []rune("string") r[0] = 'm' r = append(r, 'e') result := string(r) // "mtringe" |
| Check if rune is a white space or not | Rune | unicode.IsSpace(rune_1) |
| Check if rune is digit or not | Rune | unicode.IsDigit(rune_1) |
| Check if rune is letter or not | Rune | unicode.IsLetter(rune_1) |
| Convert byte to a rune | Rune | r := rune('a') |
| Rune of empty string | Rune | r := rune(0) |
| Compare strings | String | x==y x < y x > y |
| Replace in string | String | res1 := strings.ReplaceAll(str1, "Source", "Target") |
| Check if x string contains y string | String | strings.Contains(x, y) |
| Split the string | String | strings.Split(y, "/") |
| Join the string | String | strings.Join(y1, "/") |
| ⭐ Sort the string | String | bytes := []byte(str) sort.Slice(bytes, func(i, j int){ return bytes[i] > bytes[j]}) |
| Convert string to lower | String | s = strings.ToLower(s) |
| Convert int to float | Int | float64(3) |
| Convert int to string | Int | a := strconv.Itoa(12) |
| Convert string to int | Int | b := strconv.Atoi("string") |
| Convert int to float | Int | int(3.5) |
| Get max/min of integer | Int | math.MaxInt math.MinInt |
| Get power of a number | Int | int(math.Pow(float64(x), float64(y))) |
| Type Assertions - Typecast of generic interface to specific type | Interfaces | var input interface{} = 123 str := input.(string) |
| Get type of a variable | Interfaces | reflect.TypeOf(t1) |
| Shuffle an array | Slice | a := []int{1, 2, 3, 4, 5, 6, 7, 8} rand.Seed(time.Now().UnixNano()) rand.Shuffle(len(a), func(i, j int) { a[i], a[j] = a[j], a[i] }) |
| String range vs index | String | string[i] gives byte, while range over string, gives rune |
| Get min/max of two integers | Int | min(42, 23) - max(42, 23) |
| Compare rune with a string byte | Rune | v == '(' |
| Swap in single instruction | Any | root.Left, root.Right = root.Right, root.Left |
| Operator | Description |
|---|---|
| & | bitwise AND |
| Pipe | bitwise OR |
| ^ | bitwise XOR |
| &^ | AND NOT |
| << | left shift |
| ">>" | right shift |
m := map[rune]rune {
')': '(',
'}': '{',
']': '[',
}
if open, ok := m[v]; ok {
// element exists
}