Stdlib

172 articles
Common Patterns That Use Reflection in Go (JSON, ORM, DI) Go uses reflection in JSON marshaling, ORMs, and DI containers to dynamically inspect and manipulate types at runtime. Common Time Formatting Mistakes in Go Fix Go time formatting errors by using the required reference time string Mon Jan 2 15:04:05 MST 2006 instead of standard format codes. Complete Guide to the bytes Package in Go The Go bytes package offers efficient functions for searching, comparing, and transforming byte slices. Complete Guide to the container/list, container/heap, container/ring Packages The container/list, container/heap, and container/ring packages provide standard Go implementations for linked lists, priority queues, and circular buffers. Complete Guide to the encoding/binary Package in Go The encoding/binary package converts Go primitive types to and from byte slices using configurable byte orders. Complete Guide to the encoding/hex and encoding/base64 Packages Use encoding/hex for hexadecimal conversion and encoding/base64 for Base64 encoding/decoding in Go. Complete Guide to the fmt Package in Go The fmt package provides formatted I/O with functions like Printf for printing and Scanf for parsing in Go. Complete Guide to the math and math/big Packages in Go Use the math package for standard calculations and math/big for arbitrary-precision arithmetic with very large numbers. Complete Guide to the sort Package in Go The sort package in Go provides functions to sort slices of basic types and custom data using comparison functions. Context WithCancel Create a cancellable context using context.WithCancel to stop goroutines immediately by calling the returned cancel function. Context WithTimeout Use context.WithTimeout to create a deadline for operations in Go. Context WithValue best practices Always capture the return value of context.WithValue to use the new context and avoid memory leaks. Fix: "parsing time: cannot parse" in Go Fix the 'parsing time: cannot parse' error in Go by ensuring your layout string matches the input format using the reference time Mon Jan 2 15:04:05 MST 2006. Go Operator Precedence Table Go operator precedence determines the order of evaluation for expressions, with multiplication and shifts binding tighter than addition and comparisons. Go Operators Explained: Arithmetic, Comparison, Logical, and Bitwise Go operators perform arithmetic, comparison, logical, and bitwise actions on values, enabling the compiler to optimize code execution. How Defer Works with Functions in Go: Order and Gotchas Go executes deferred functions in reverse order of their appearance, evaluating arguments immediately at the time of deferral. How Tail Calls Work in Go (Spoiler: No TCO) Go does not support tail call optimization, so tail-recursive functions will consume stack space and may overflow. How to Add or Subtract Time in Go with time.Duration Use the `time.Duration` type to represent time intervals and add or subtract them from a `time.Time` value using the built-in `Add()` and `Sub()` methods. How to Append to a Slice in Go Use the built-in `append()` function to add elements to a slice, which automatically handles capacity expansion and returns a new slice header. How to Calculate the Difference Between Two Times in Go Calculate the time difference between two Go time.Time values by subtracting the earlier time from the later one using the Sub() method. How to Calculate the Start and End of a Day, Month, or Year in Go Calculate start and end times for days, months, and years in Go using the time.Date method and duration arithmetic. How to Chain Methods in Go (Fluent Interface) Go requires explicit pointer returns in methods to enable manual method chaining, as it lacks native fluent interface support. How to Compare Times in Go (Before, After, Equal) Compare Go time values using the Before, After, and Equal methods on time.Time objects. How to Convert Between Time Zones in Go Convert Go time.Time values between time zones using time.LoadLocation and the In method. How to Convert Unix Timestamp to time.Time in Go Convert a Unix timestamp to Go's time.Time using the time.Unix function with seconds and nanoseconds arguments. How to Create a Linked List in Go Go does not provide a built-in linked list type, so you must define your own struct to represent nodes and manually manage the pointers connecting them. How to Create and Initialize a Slice in Go Create a Go slice using the make function for specific capacity or slice literals for immediate values. How to Create a Self-Signed Certificate in Go Generate a self-signed certificate in Go using crypto/x509 to create a private key and certificate file for local testing or development. How to Create a Stack and Queue in Go Implement stacks and queues in Go using slices with append and slicing operations for push/pop and enqueue/dequeue logic. How to create HTTP server Start a Go HTTP server by defining a handler function and calling http.ListenAndServe with your desired port. How to Create Values Dynamically with reflect.New Use reflect.New with a reflect.Type to dynamically allocate a zero-valued pointer to any Go type. How to Define and Call Functions in Go Define Go functions with the func keyword and parameters, then call them by name with matching arguments. How to Define Methods on Types in Go Define Go methods by adding a receiver argument in parentheses before the function name to attach behavior to a type. How to Delete an Element from a Slice in Go Delete a Go slice element by swapping it with the last item and truncating the slice length. How to Encode and Decode Base64 in Go Encode and decode Base64 strings in Go using the standard encoding/base64 package functions. How to Encrypt Data with AES in Go (GCM Mode) Encrypt data in Go using AES-GCM by creating a cipher from a key and sealing plaintext with a random nonce. How to Encrypt Data with RSA in Go Use the `crypto/rsa` package to generate a key pair, then encrypt data with the public key using PKCS#1 v1.5 or OAEP padding, and decrypt it with the private key. How to Format a Time in Go (The Reference Time: Mon Jan 2 15:04:05 MST 2006) Format a Go time value using the reference time string Mon Jan 2 15:04:05 MST 2006 with the Format method. How to Generate and Use Ed25519 Keys in Go Generate Ed25519 keys in Go using crypto/ed25519.GenerateKey and verify signatures with ed25519.Verify. How to Generate PDF Files in Go Go has no built-in PDF generation; you must use a third-party library like `unidoc` or `go-pdf`. How to Generate Random Numbers and Bytes in Go (crypto/rand) Generate secure random bytes and integers in Go using the crypto/rand package for cryptographic safety. How to Generate RSA Key Pairs in Go Generate RSA key pairs in Go using crypto/rand and crypto/rsa packages. How to Get the Current Time in Go Use `time.Now()` from the standard `time` package to get the current local time, or `time.Now().UTC()` for Coordinated Universal Time. How to Get the Day of the Week in Go Get the current day of the week in Go using the time.Now().Weekday() method. How to Get the Type and Kind of a Value with Reflection Get a value's type and kind at runtime using the reflect.TypeOf and reflect.ValueOf functions. How to Get Unix Timestamp in Go Use `time.Now().Unix()` to get the current Unix timestamp in seconds, or `time.Now().UnixNano()` for nanoseconds. How to handle cookies in Go Go handles cookies manually using the net/http package to read and write http.Cookie objects. How to Handle Monotonic Clocks in Go Go uses monotonic clocks automatically for duration calculations via time.Now() and time.Since() to ensure accuracy despite system clock changes. How to Handle Multiple Return Values in Go Return multiple values in Go by listing them in parentheses and assigning them to multiple variables or ignoring extras with the blank identifier. How to Handle Pluralization in Go Go lacks built-in pluralization, requiring manual logic or external libraries to handle singular and plural forms. How to Handle Unicode and UTF-8 in Go Go natively supports UTF-8 strings and uses runes for Unicode code points, requiring no manual encoding conversion. How to Hash Data with MD5 in Go (And Why You Shouldn't) Use crypto/md5 for legacy checksums only; avoid MD5 for security and use SHA-256 instead. How to Hash Data with SHA-256 in Go Use the `crypto/sha256` package from the standard library to compute hashes, either by creating a hash object and writing data to it or by calling the convenient `Sum256` function for simple byte slices. How to Implement a Binary Search Tree in Go Implement a Binary Search Tree in Go using a recursive node struct with insert and search methods. How to Implement a Bloom Filter in Go Use the `hash/maphash` package to create a Bloom filter that supports probabilistic set membership with configurable false-positive rates. How to Implement a Custom Binary Protocol Parser in Go Use encoding/binary to read fixed-size fields from an io.Reader into a Go struct for custom binary protocol parsing. How to Implement a Graph in Go (Adjacency List) Implement a Go graph using a map of integer slices to represent an adjacency list structure. How to Implement a Hash Map from Scratch in Go Implement a Go hash map by defining a struct with a bucket slice, using maphash for key hashing, and handling collisions via chaining. How to Implement a Linked List in Go Define a Node struct with a Next pointer and implement Append and Print methods to manage the chain. How to Implement a LRU Cache in Go Implement an LRU cache in Go using container/list and a map to store and evict the least recently used items automatically. How to Implement a Priority Queue (Heap) in Go Implement a Go priority queue by defining a custom type that satisfies the container/heap.Interface methods. How to Implement a Queue in Go Implement a circular queue in Go using a slice, a head index, and modulo arithmetic to manage fixed capacity efficiently. How to Implement a Ring Buffer in Go Implement a Go ring buffer using a slice with head/tail indices and modulo arithmetic for wrapping. How to Implement a Stack in Go Implement a stack in Go using a struct with a slice and Push/Pop methods for LIFO operations. How to Implement a Trie in Go Implement a Trie in Go using a struct with a map of children nodes and methods to insert and search for words. How to Implement BFS and DFS in Go Implement BFS using a queue and DFS using a stack or recursion to traverse graphs or trees in Go. Use a `queue` slice for BFS and a recursive function or `stack` slice for DFS. How to Implement Binary Search in Go (sort.Search, slices.BinarySearch) Use slices.BinarySearch for Go 1.21+ or sort.Search with a comparison function for older versions to efficiently find items in sorted slices. How to Invoke Methods with Reflection in Go Use the reflect package's MethodByName and Call functions to dynamically invoke methods in Go. How to Iterate Over Struct Fields with Reflection in Go Iterate over Go struct fields at runtime using the reflect package's ValueOf, Type, and Field methods. How to make HTTP requests Use the standard library's `net/http` package for most cases, as it provides a robust, dependency-free client with built-in support for timeouts and TLS. How to Parse a Date String in Go Parse a date string in Go using time.Parse with the 2006-01-02 reference layout. How to Parse and Format Numbers as Strings in Go Convert Go numbers to strings using strconv.FormatInt and parse them back using strconv.ParseInt. How to Parse and Generate HTML in Go (golang.org/x/net/html) Use the `golang.org/x/net/html` package to parse HTML into a tree of nodes and generate HTML by walking that tree. The parser returns a `*html.Node` representing the document root, which you can traverse recursively to read or modify content, then serialize back to a string using `html.Render`. How to Parse and Generate X.509 Certificates in Go Parse X.509 certificates with x509.ParseCertificate and generate them using x509.CreateCertificate in Go. How to parse JSON Parse JSON in Go using the encoding/json package's Unmarshal function to convert data into native variables. How to Parse PDF Files in Go Use a third-party library like unidoc or go-pdf to parse PDF files in Go, as the standard library lacks native support. How to Pass a Slice to a Variadic Function in Go Pass a slice to a variadic Go function by using the spread operator (...) to unpack its elements as individual arguments. How to Process Images in Go (image Package) Load images with the image package and manipulate pixels using image/draw to create or modify graphics in Go. How to Read and Set Struct Fields with Reflection Use reflect.ValueOf and FieldByName to read or set struct fields dynamically by name. How to Read and Write Excel Files in Go (excelize) Use the excelize library in Go to create new Excel workbooks, set cell values, and save files with minimal code. How to read and write files Read files with os.ReadFile and write files with os.WriteFile in Go. How to Read and Write Parquet Files in Go The Go standard library does not natively support Parquet files; you must use a third-party library like `github.com/xitongsys/parquet-go`. Install the library, import it, and use `parquet.WriteParquetFile` to write and `parquet.ReadParquetFile` to read data. How to Read Struct Tags with Reflection in Go Read Go struct tags at runtime using reflect.TypeOf to get the struct type and Field.Tag.Get to extract specific tag values. How to Remove Duplicates from a Slice in Go Remove duplicates from a Go slice by tracking seen items in a map and appending unique values to a new slice. How to Resize and Crop Images in Go TITLE: How to Resize and Crop Images in Go How to Return Multiple Values from a Function in Go Return multiple values in Go by listing types in the function signature and separating return values with commas. How to set HTTP headers Set HTTP headers in Go by using the Header.Set method on Request or ResponseWriter objects, or control HTTP behavior via GODEBUG environment variables. How to Sign and Verify Data with RSA or ECDSA in Go Sign and verify data in Go using the crypto/rsa and crypto/ecdsa packages with SHA256 hashing. How to Sort Custom Types in Go Implement Len, Less, and Swap methods on your type to satisfy sort.Interface, then call sort.Sort to order your custom data. How to Truncate and Round Time in Go Truncate rounds time down to a duration, while Round snaps it to the nearest duration in Go. How to Use Argon2 for Password Hashing in Go Use the golang.org/x/crypto/argon2 package to generate and verify password hashes with random salts and constant-time comparison. How to use atomic operations Use the `sync/atomic` package when you need lock-free, thread-safe updates to simple variables like integers, pointers, or booleans, avoiding the overhead of `sync.Mutex` for high-frequency counters or flags. How to Use Bcrypt for Password Hashing in Go Hash passwords in Go using the bcrypt package to securely store and verify user credentials without storing plain text. How to Use Bitwise Operators in Go Use Go's bitwise operators like &, |, and << to manipulate individual bits in integer values for efficient flag management and data processing. How to Use break and continue in Go Loops Use break to exit a loop immediately and continue to skip the current iteration and proceed to the next one. How to use bufio for buffered IO Wrap io.Reader or io.Writer with bufio.NewReader or bufio.NewWriter to buffer data and reduce system calls for efficient I/O. How to Use Callbacks in Go Export Go functions to C using the //export directive to enable C code to call back into your Go program. How to Use container/heap in Go Use container/heap by defining a type that implements the heap.Interface methods and calling heap.Init, Push, and Pop. How to Use container/list (Doubly Linked List) in Go Create a doubly linked list in Go using the container/list package to efficiently add, remove, and iterate over elements. How to Use container/ring in Go The `container/ring` package provides a circular linked list data structure for storing elements in a fixed-size loop. Create a new ring with `New(n)`, set the `Value` field of each node to store data, and use `Next()` or `Prev()` to traverse the list. How to use context package Use the context package to manage deadlines, cancellation, and request-scoped values across goroutines and API boundaries. How to use crypto package The Go `crypto` package is a meta-package that organizes cryptographic functionality into sub-packages; you never import `crypto` directly but instead import specific sub-packages like `crypto/sha256` for hashing or `crypto/rand` for secure random number generation. How to use database sql Use the `database/sql` package as a generic interface to connect to any SQL database, then register a specific driver (like `pgx` for PostgreSQL or `mysql` for MySQL) to handle the actual connection details. How to use embed package Use the `embed` package to compile static files directly into your Go binary at build time, eliminating the need for external file dependencies or runtime file system access. How to Use encoding/binary for Byte-Level Operations Use encoding/binary to safely convert integers and floats to byte slices with specific endianness for binary data handling. How to use encoding package Go has no single encoding package; use specific subpackages like encoding/json or encoding/base64 for your data format. How to Use fallthrough in Go Switch Statements Use `fallthrough` in a Go switch statement to explicitly execute the code block of the next case immediately after the current one finishes, bypassing the default behavior of stopping after a case matches. How to use filepath package Use the filepath package to build and manipulate portable file paths across different operating systems. How to use flag package Import flag, define variables, bind them with flag functions, call flag.Parse(), and use the variables in your code. How to Use Functions as First-Class Values in Go Go treats functions as first-class values, allowing them to be assigned to variables, passed as arguments, and returned from other functions. How to Use Generic Data Structures in Go Go 1.18+ introduced generics, allowing you to write reusable data structures that work with any type while maintaining compile-time type safety. How to Use goto in Go (And Why You Usually Shouldn't) Use goto to jump to a label in Go, but prefer structured control flow for readability. How to Use HMAC for Message Authentication in Go Generate and verify message authentication codes in Go using the crypto/hmac package with a secure hash function like SHA-256. How to use html template package Import the html/template package from the Go standard library and use template.New().Parse() to create safe, dynamic HTML content. How to Use If with a Short Statement in Go Use the := operator inside the if statement's initialization clause to declare a variable scoped only to that block. How to use io package The `io` package provides fundamental interfaces and helper functions for generic I/O operations, allowing you to work with streams of data without needing to know the underlying source or destination. How to Use Labels with break and continue in Go Go labels let break and continue statements target specific loops to exit or skip multiple nested levels instantly. How to Use maps and slices Packages from Go Standard Library Use the maps and slices packages in Go 1.21+ to easily sort, copy, and manipulate maps and slices with built-in utility functions. How to Use message.Printer for Localized Formatting in Go Use fmt.Printf for basic output or golang.org/x/text/message for localized formatting since message.Printer is not in the standard library. How to Use Method Sets in Go Use the GODEBUG environment variable or go.mod directives to control Go runtime behavior and manage backwards compatibility. How to Use Named Return Values in Go Named return values in Go allow you to declare return variable names in the function signature for automatic return and cleaner code. How to use net http Client Use http.Client to send requests, customize settings like timeout, and always close response bodies for proper connection reuse. How to use net package for TCP Use net.Dial to establish a TCP connection and the Conn interface to read and write data. How to use os exec package Use the os/exec package to spawn external processes by calling exec.Command and running them with .Output() or .Run(). How to use regexp package Compile patterns with regexp.MustCompile and use MatchString to check if text matches your criteria. How to use sort package Use the sort package to arrange slices of integers, strings, or custom types in ascending or descending order. How to use strconv package The strconv package provides functions to convert strings to integers, floats, and booleans, and vice versa. How to use strings package Use the built-in strings package to search, split, and transform text efficiently in Go. How to Use Switch Without a Condition in Go (Tagless Switch) Use a tagless switch in Go by omitting the expression after the switch keyword to execute cases based on boolean conditions. How to use sync Map Use sync.Map for concurrent read-heavy workloads by initializing it and using Load, Store, and Delete methods. How to use sync Once Use sync.Once with the Do method to ensure a function runs exactly once across concurrent goroutines. How to use sync package The sync package provides basic synchronization primitives like WaitGroup, Mutex, and Once to coordinate goroutines safely. How to use sync Pool Use sync.Pool to cache and reuse objects by calling Get() to retrieve and Put() to return them, reducing allocation overhead. How to use testing package Write Test functions with *testing.T arguments and run them using go test to automate verification of your Go code. How to use text template package Import text/template, parse a template string with placeholders, and execute it with a data map to generate dynamic text. How to Use the cmp Package for Comparison Functions Use `cmp.Compare` to compare two values of the same type, returning -1, 0, or 1 to indicate less than, equal, or greater than. This function replaces manual comparison logic for any comparable type. How to Use the crypto/elliptic Package in Go Use crypto/elliptic to select standard curves like P256 and perform point operations for cryptographic math. How to Use the crypto/tls Package in Go Use crypto/tls to create secure connections by wrapping a net.Conn with tls.Client or tls.Server and a tls.Config. How to Use the Functional Options Pattern in Go Use variadic functions that accept option functions to flexibly configure Go structs without bloating your constructor API. How to Use the golang.org/x/text Package for i18n Use golang.org/x/text/language and message packages to detect locales and format localized strings in Go applications. How to Use the maps and slices Packages from the Standard Library The `maps` and `slices` packages are standard library utilities added in Go 1.21 to provide common operations on maps and slices without requiring external dependencies. Import them and use their exported functions directly on your data structures. How to Use the Range Keyword in Go The range keyword in Go iterates over collections like slices and maps, returning the index/key and value for each element. How to Use the reflect Package in Go Use the reflect package to inspect Go types and values at runtime for dynamic programming tasks. How to Use the Shift Operators << and >> in Go Use the `<<` operator to shift bits left (multiplying by powers of 2) and `>>` to shift bits right (dividing by powers of 2), keeping in mind that Go shifts are always unsigned for the count and preserve the sign bit for signed integers during right shifts. How to Use the slices and maps Packages (Generic Standard Library) Use the slices and maps packages to perform common operations like sorting, copying, and searching on Go slices and maps with generic functions. How to Use the strconv Package in Go The strconv package provides functions to convert Go values to and from string representations for numbers and booleans. How to Use the unicode and unicode/utf8 Packages The unicode and unicode/utf8 packages automatically support Unicode 17 in Go, providing functions to validate, count, and classify characters without manual configuration. How to use time package Import the time package to get current timestamps, pause execution, and measure durations in Go. How to Use time.Since and time.Until in Go Use time.Since to calculate elapsed time from a past moment and time.Until to calculate remaining time until a future deadline. How to Work with Avro in Go Use the goavro library to define schemas and encode/decode data in Go for efficient binary serialization. How to Work with CSV Strings in Go Parse CSV strings in Go by wrapping the string in strings.NewReader and using the encoding/csv package to read records. How to Work with PNG, JPEG, and GIF in Go Use the `image`, `image/png`, `image/jpeg`, and `image/gif` packages in the standard library to decode and encode these formats. The `image.Decode` function automatically detects the format from the file content, while `image/png.Encode`, `image/jpeg.Encode`, and `image/gif.Encode` handle saving. How to Write an Infinite Loop in Go Use a `for` loop with no initialization, condition, or post-statement, which is the idiomatic way to create an infinite loop in Go. How to Write a While Loop in Go Using for Go does not have a dedicated `while` keyword; instead, you use the `for` statement with a condition and no initialization or post statements to create a while loop. How to Write For Loops in Go (The Only Loop) Go uses a single `for` loop construct that supports standard, while, and infinite loop patterns by adjusting its three components. How to Write If-Else Statements in Go Write Go if-else statements using the if keyword, a boolean condition, and curly braces to define true and false execution paths. How to Write Recursive Functions in Go Recursive functions in Go are written by defining a function that calls itself with a modified argument, ensuring a base case exists to terminate the recursion and prevent stack overflow. How to Write Switch Statements in Go Use Go switch statements to execute different code blocks based on a variable's value or boolean conditions. Passing context through layers Always pass the `context.Context` as the first argument to every function in your call chain, from the entry point down to the database or external service calls. The Copy Built-in Copies Min(len(src), len(dst)) Elements bytes.Copy returns the number of bytes copied, which is the minimum of the source and destination slice lengths. Underrated Standard Library Packages in Go You Should Know Discover powerful built-in Go packages like archive/tar and runtime/metrics that solve common problems without external dependencies. What Are the Common Function Signature Patterns in Go Go function signatures define inputs and outputs using the syntax func Name(params) (returns) with explicit types. What Are Variadic Functions in Go (... Syntax) Variadic functions in Go use the ... syntax to accept a flexible number of arguments as a slice. What Is a Higher-Order Function in Go A higher-order function in Go accepts functions as arguments or returns them, enabling flexible and reusable code patterns. What Is Reflection in Go and When to Use It Reflection in Go allows runtime inspection and modification of types via the reflect package, ideal for generic libraries but costly for performance. What Is Short-Circuit Evaluation in Go Short-circuit evaluation in Go stops evaluating logical expressions as soon as the result is determined by the first operand. What Is the Difference Between a Function and a Method in Go Functions are standalone code blocks, while methods are functions bound to a specific type via a receiver. What Is the Difference Between Arrays and Slices in Go Arrays are fixed-size value types, while slices are dynamic reference types that view underlying arrays. What Is the Difference Between for range and for i in Go Use for range for reading slices and for i loops when modifying slice elements. When to Avoid Reflection in Go Avoid Go reflection for performance-critical code or when static typing is possible, as it is slower and less safe than direct type access. Why Go Uses a Reference Time Instead of strftime Patterns Go uses a reference time format to ensure consistent, locale-independent date formatting by using a concrete example as a template. Why Map Iteration Order Is Random in Go Go map iteration order is random because the language specification explicitly requires it to prevent code from relying on a specific order. The runtime shuffles the internal hash table layout on every run to ensure this non-determinism.