Writing

Programming

An Introduction to the io_uring Asynchronous I/O Framework | linux

Interrupt driven – By default, the io_uring instance is setup for interrupt driven I/O. I/O may be submitted using io_uring_enter() and can be reaped by checking the completion queue directly. Polled – Perform busy-waiting for an I/O completion, as opposed to getting notifications via an asynchronou…

Read article →

Lecture 11: Type Inference

The key is to reframe the question ... type is, yet, but we can deduce certain facts about it. This process is called type-inference, and we will follow the classic Hindley-Milner algorithm to deduce types for our programs....

Read article →

How to Build an LSM Tree Storage Engine from Scratch – Full Handbook

We’ll discuss this again below when we’re talking about compaction. With this approach, we either have the old valid MANIFEST or the new valid MANIFEST, never a partially written corrupted file. From an integration standpoint, NewDB will read the manifest and set its SSTable slice based on that. The…

Read article →

Algebraic Effects for Functional Programming

Figure 6. Type rules for explicitly typed Koka · too much resources to run reliably. A better approach was ... System F [15] extended with the effect annotations. In par- ticular, lambda’s carry the effect of the body as ϵ. Similarly, handlers are annotated with the handled effect type l.

Read article →

Rust Borrow Checker

Instead of taking Vec<i32>s as our arguments, we take a reference: &Vec<i32>. And instead of passing v1 and v2 directly, we pass &v1 and &v2. We call the &T type a ‘reference’, and rather than owning the resource, it borrows ownership. A binding that borrows something does not deallocate the resourc…

Read article →

Functors · OCaml Documentation

Module System Modules Functors First-Class Modules Libraries With Dune · Data Structures Options Arrays Maps Sets Hash Tables Sequences CS3110 Memoization CS3110 Monads · Advanced Topics Preprocessors and PPXs Operators Objects · Runtime & Compiler RWO Memory Representation of Values RWO Understandi…

Read article →

All About Monads - HaskellWiki

Any instance of the Monad class can be used in a do-block in Haskell. In short, the do notation allows you to write monadic computations using a pseudo-imperative style with named variables. The result of a monadic computation can be "assigned" to a variable using a left arrow <- operator.

Read article →

Fearless Concurrency

When we run the code in Listing 16-8, we’ll see the value printed from the main thread: ... The ownership rules play a vital role in message sending because they help you write safe, concurrent code. Preventing errors in concurrent programming is the advantage of thinking about ownership throughout …

Read article →

Coroutines | Kotlin Documentation

Most coroutine features are provided by the kotlinx.coroutines library, which includes tools for launching coroutines, handling concurrency, working with asynchronous streams, and more. If you're new to coroutines in Kotlin, start with the Coroutine basics guide before diving into more complex topic…

Read article →

Tutorial | Tokio - An asynchronous Rust runtime

When writing asynchronous code, you cannot use the ordinary blocking APIs provided by the Rust standard library, and must instead use asynchronous versions of them. These alternate versions are provided by Tokio, mirroring the API of the Rust standard library where it makes sense.

Read article →

Basic MetaProgramming in Zig

The first part, the switch, ensures that T is a struct, union, enum of an opaque, else it returns false. We saw how hasFn returns false for other types, whereas @hasDecl gives a comptime error. Here we see how @typeInfo can be used to turn that compile time error into value.

Read article →

How to Use sync.Pool for Object Reuse in Go

/* Benchmark Analysis Guide: 1. ns/op (nanoseconds per operation) - Lower is better - Pool typically shows 2-5x improvement 2. B/op (bytes allocated per operation) - Pool should show significant reduction - Target: 0 or near-zero for hot paths 3. allocs/op (allocations per operation) - Pool should r…

Read article →

Go synctest: Solving Flaky Tests

synctest is a new feature introduced in Go 1.24. It enables deterministic testing of concurrent code by running goroutines in controlled, isolated environments.

Read article →

Fixing For Loops in Go 1.22 - The Go Programming Language

For Go 1.22, we plan to change for loops to make these variables have per-iteration scope instead of per-loop scope. This change will fix the examples above, so that they are no longer buggy Go programs; it will end the production problems caused by such mistakes; and it will remove the need ...

Read article →

reflect package - reflect - Go Packages

SliceOf returns the slice type with element type t. For example, if t represents int, SliceOf(t) represents []int. ... StructOf returns the struct type containing fields. The Offset and Index fields are ignored and computed as they would be by the compiler. StructOf currently does not support promot…

Read article →

Data Race Detector - The Go Programming Language

The fix is to introduce new variables in the goroutines (note the use of :=): ... _, err := f1.Write(data) ... _, err := f2.Write(data) ... If the following code is called from several goroutines, it leads to races on the service map. Concurrent reads and writes of the same map are not safe:

Read article →

Profile-guided optimization - The Go Programming Language

The standard approach to building is to store a pprof CPU profile with filename default.pgo in the main package directory of the profiled binary. By default, go build will detect default.pgo files automatically and enable PGO. Committing profiles directly in the source repository is recommended as p…

Read article →

How to Implement Token Bucket Rate Limiting in Go

Always initialize buckets with full capacity. Otherwise, legitimate clients get rate limited on their very first request. Not handling time drift. If your server's clock jumps forward (NTP sync, VM migration), you might add way too many tokens.

Read article →

How to Handle HTTP Client Timeouts Properly in Go

// Create a custom transport with fine-grained timeout control transport := &http.Transport{ // Maximum time to wait for a TCP connection to be established DialContext: (&net.Dialer{ Timeout: 10 * time.Second, // Connection timeout KeepAlive: 30 * time.Second, // TCP keepalive interval }).DialContex…

Read article →

Graceful Shutdown in Go: Practical Patterns

It is a good practice to reserve about 20 percent of the time as a safety margin to avoid being killed before cleanup finishes. This means aiming to finish everything within 25 seconds to avoid data loss or inconsistency. When using net/http, you can handle graceful shutdown by calling the http.Serv…

Read article →

Basics tutorial | Go | gRPC

Use the Go gRPC API to write a simple client and server for your service. It assumes that you have read the Introduction to gRPC and are familiar with protocol buffers. Note that the example in this tutorial uses the proto3 version of the protocol ...

Read article →

Go Wiki: TableDrivenTests - The Go Programming Language

More importantly, map iteration order isn’t specified nor is it even guaranteed to be the same from one iteration to the next. This ensures that each test is independent of the others and that testing order doesn’t impact results. Parallelizing table tests is simple, but requires precision to avoid …

Read article →

Logging in Go with Slog: A Practitioner's Guide · Dash0

While slightly more verbose, using slog.AttrCopy is the only right way to log in Go. It ensures your logs are always well-formed, reliable, and safe from runtime surprises. While using slog.AttrCopy is the safer approach, there’s nothing stopping ...

Read article →

Profiling Go Programs - The Go Programming Language

Benchmarks are only as good as the programs they measure. We used go tool pprof to study an inefficient Go program and then to improve its performance by an order of magnitude and to reduce its memory usage by a factor of 3.7. A subsequent comparison with an equivalently optimized C++ program ...

Read article →

How to Use Context in Go for Cancellation and Timeouts

package main import ( "context" "fmt" "net/http" "time" ) func handler(w http.ResponseWriter, r *http.Request) { // r.Context() is cancelled when: // - Client disconnects // - Request times out // - Handler returns ctx := r.Context() // Add our own timeout ctx, cancel := context.WithTimeout(ctx, 5*t…

Read article →

How to Handle Errors Effectively in Go

package main import ( "errors" "fmt" "net" ) func connectToServer(addr string) error { conn, err := net.Dial("tcp", addr) if err != nil { return fmt.Errorf("connecting to server: %w", err) } defer conn.Close() return nil } func main() { err := connec…

Read article →

Scala vs. GO. Introduction | by Javier Ramos | ITNEXT

Go, in the other hand, is a newer, simpler language created by Google to overcome the criticisms of C++; designing a language with multi core processors in mind. Both are great languages that can achieve great performance for concurrent applications and stream processing but their design is quite di…

Read article →

Go vs Scala | Know The 8 Most Amazing Differences

Back to Scala vs Go based on this model, GO provides a more straightforward and smaller set of orthogonal primitives that easily interact with ease and are expected. A developer can quickly build his need by learning a small number of primitives, ...

Read article →