Programming Notes ✍️ – Telegram
Programming Notes ✍️
12 subscribers
65 photos
1 file
22 links
Download Telegram
Go is lexically scoped using blocks:



The scope of a predeclared identifier is the universe block.
The scope of an identifier denoting a constant, type, variable, or function (but not method) declared at top level (outside any function) is the package block.
The scope of the package name of an imported package is the file block of the file containing the import declaration.
The scope of an identifier denoting a method receiver, function parameter, or result variable is the function body.
The scope of an identifier denoting a type parameter of a function or declared by a method receiver begins after the name of the function and ends at the end of the function body.
The scope of an identifier denoting a type parameter of a type begins after the name of the type and ends at the end of the TypeSpec.
The scope of a constant or variable identifier declared inside a function begins at the end of the ConstSpec or VarSpec (ShortVarDecl for short variable declarations) and ends at the end of the innermost containing block.
The scope of a type identifier declared inside a function begins at the identifier in the TypeSpec and ends at the end of the innermost containing block.
Types:
any bool byte comparable
complex64 complex128 error float32 float64
int int8 int16 int32 int64 rune string
uint uint8 uint16 uint32 uint64 uintptr

Constants:
true false iota

Zero value:
nil

Functions:
append cap clear close complex copy delete imag len
make max min new panic print println real recover
Within a type parameter list of a generic type T, a type constraint may not (directly, or indirectly through the type parameter list of another generic type) refer to T.



type T1[P T1[P]] … // illegal: T1 refers to itself
type T2[P interface{ T2[int] }] … // illegal: T2 refers to itself
type T3[P interface{ m(T3[int])}] … // illegal: T3 refers to itself
type T4[P T5[P]] … // illegal: T4 refers to T5 and
type T5[P T4[P]] … // T5 refers to T4

type T6[P int] struct{ f *T6[P] } // ok: reference to T6 is not in type parameter list
The length of a slice may be changed as long as it still fits within the limits of the underlying array; just assign it to a slice of itself. The capacity of a slice, accessible by the built-in function cap, reports the maximum length the slice may assume. Here is a function to append data to a slice. If the data exceeds the capacity, the slice is reallocated. The resulting slice is returned. The function uses the fact that len and cap are legal when applied to the nil slice, and return 0.
slice > array[len]
if array[len] == len[arr] > new(arr[len(arr)+1] = "data") > copy to addr arr > replace
Programming Notes ✍️
slice > array[len] if array[len] == len[arr] > new(arr[len(arr)+1] = "data") > copy to addr arr > replace
func Append(slice, data []byte) []byte {
l := len(slice)
if l + len(data) > cap(slice) { // reallocate
// Allocate double what's needed, for future growth.
newSlice := make([]byte, (l+len(data))*2)
// The copy function is predeclared and works for any slice type.
copy(newSlice, slice)
slice = newSlice
}
slice = slice[0:l+len(data)]
copy(slice[l:], data)
return slice
}
Programming Notes ✍️
https://medium.com/@nur_islam/design-a-least-recently-used-lru-cache-in-go-golang-298d4ce3f3ec
package main

import (
"log"
"time"
)

type LRUCache struct {
NodeMap map[int]Node
Cap int
}

func NewLRUCache(c int) *LRUCache {
return &LRUCache{
Cap: c,
NodeMap: make(map[int]Node, c),
}
}

type Node struct {
value int
lastUsed time.Time
}

// Put ...
func (lru *LRUCache) Put(key, value int) {
mSize := len(lru.NodeMap)
var leastRecentUsedKey int
leastRecentUsedValue := time.Now()

// remove if the max size reached
if mSize >= lru.Cap {
// remove most recent one
for key, v := range lru.NodeMap {
if v.lastUsed.Before(leastRecentUsedValue) {
leastRecentUsedKey = key
leastRecentUsedValue = v.lastUsed
}
}

delete(lru.NodeMap, leastRecentUsedKey)
}

lru.NodeMap[key] = Node{
value: value,
lastUsed: time.Now(),
}
}

// Get ...
func (lru *LRUCache) Get(key int) int {
val, prs := lru.NodeMap[key]

if prs {
return val.value
}
return -1
}

func main() {
// create lru with size specified
lru := NewLRUCache(5)

// check no value case -> return -1
log.Println(lru.Get(1))

// use of put
lru.Put(1, 1)
lru.Put(2, 2)

// use of get
log.Println(lru.Get(1))
log.Println(lru.Get(2))
}



/*

Design a data structure that follows the constraints of a Least Recently Used (LRU) cache.

Implement the LRUCache class:

* LRUCache(int capacity) Initialize the LRU cache with positive size capacity.
* int get(int key) Return the value of the key if the key exists, otherwise return -1.
* void put(int key, int value) Update the value of the key if the key exists.
Otherwise, add the key-value pair to the cache.
If the number of keys exceeds the capacity from this operation, evict the least recently used key.

*/
How to choose the right pattern

Rough mental checklist:

I have multiple identical units of work → worker pool (with a job channel).

I have multi-stage processing → pipeline + fan-out/fan-in.

I just need to safely share and mutate some data → mutex / RWMutex, maybe atomics.

I need to limit concurrency → semaphore via buffered channel or worker pool size.

I need cancellation/timeout → context.Context + select.

I’m overcomplicating things with channels → step back, consider a simple mutex.
A thread is a single sequence stream within a process. Threads are also called lightweight processes as they possess some of the properties of processes. Each thread belongs to exactly one process.
What STAR stands for
Situation - the situation you had to deal with
Task - the task you were given to do
Action - the action you took
Result - what happened as a result of your action and what you learned from the experience
# Demonstrating (mis)use of special methods
class SillyClass:
def getitem(self, key):
""" Determines behavior of self[key] """
return [True, False, True, False]

def pow(self, other):
""" Determines behavior of self ** other """
return "Python Like You Mean It"