BudiBadu Logo

Samplebadu

Code with Example
BudiBadu Logo
Samplebadu
Go (Golang)

Learn Go (Golang) by Examples

Go 1.23

Go is a statically typed, compiled programming language designed at Google. It is syntactically similar to C, but with memory safety, garbage collection, structural typing, and CSP-style concurrency. Known for its simplicity and efficiency, Go is widely used for building scalable web services, cloud applications, and system tools. These code examples demonstrate real-world Go programming patterns.

This page provides comprehensive code samples to help learners understand Go from basics to advanced concepts. Each example includes complete, runnable code with line numbers, detailed explanations, and line-by-line breakdowns to ensure you grasp every concept thoroughly.

Hello World

Your first Go program - the traditional starting point for learning any programming language. This code sample demonstrates the basic structure of a Go application, including the package declaration, import statement, and the main function entry point. It serves as a fundamental introduction to Go's syntax and executable structure.

Values

Understanding Go's basic value types is crucial for writing robust applications. This code example explores strings, integers, floats, and booleans, demonstrating how to work with literals, perform arithmetic and logical operations, and understand the behavior of Go's strongly-typed system.

Variables

Learn the various ways to declare and initialize variables in Go. This example covers the standard `var` keyword, type inference, multiple variable declarations, zero values, and the concise short declaration syntax `:=`, providing a complete overview of variable management in Go.

Constants

Explore how to declare and use constants in Go. This sample demonstrates defining immutable values that are evaluated at compile time, including typed and untyped constants, and explains their role in creating safer and more efficient code.

Basic Arithmetic

Perform arithmetic operations in Go with this comprehensive example. It covers addition, subtraction, multiplication, division, and modulus, while also highlighting important concepts like integer vs. floating-point division and the necessity of explicit type conversions in mixed-type operations.

Strings and Runes

Dive into Go's handling of text with Strings and Runes. This example explains the difference between bytes and Unicode code points (runes), demonstrating how to correctly iterate over UTF-8 encoded strings and access individual characters.

Methods

Learn how to define methods on types in Go, a key aspect of its object-oriented capabilities. This example distinguishes between value receivers and pointer receivers, explaining when to use each for efficiency and state modification.

Interfaces

Explore Interfaces in Go, a powerful tool for defining behavior and achieving polymorphism. This example shows how to define interfaces, implement them implicitly with structs, and write flexible code that accepts any type satisfying an interface.

Keywords

An overview of Go's 25 reserved keywords. This example demonstrates a program that utilizes a wide variety of these keywords in context, illustrating their roles in declarations, control flow, and type definitions.

Toolchain

Go comes with a powerful, built-in toolchain for building, testing, and formatting code. This example demonstrates a standard Go file and explains how to use commands like `go build`, `go run`, `go fmt`, and `go vet` to manage your project lifecycle.

Modules

Go Modules are the official dependency management system for Go. This example shows how to import external packages and explains the workflow for initializing modules, adding dependencies, and maintaining the `go.mod` and `go.sum` files.

Naming Conventions

Go has strict and opinionated naming conventions that directly affect symbol visibility and code readability. This example covers `MixedCaps`, package naming, interface naming, and the "Effective Go" guidelines for variable length.

Comments

Comments in Go serve two purposes: explaining code to developers and generating documentation via `godoc`. This example shows how to write effective package, function, and line comments, as well as how to use directives.

Zero Values

In Go, variables declared without an initial value are given their "zero value". This example explains what these values are for different types and demonstrates the "Make the zero value useful" proverb with structs like sync.Mutex.

Type Inference

Go compiler can deduce the type of a variable from its initialization value. This example demonstrates type inference with `var` and the short declaration operator `:=`, and explains when to use each.

Type Conversion

Go is a strongly typed language and does not support implicit type conversion. This example shows how to explicitly convert between types like int, float, and string using direct casting and the `strconv` package.

Numeric Types

A comprehensive guide to Go's integer, floating-point, and complex number types. This example explains the difference between architecture-dependent types (int, uint) and fixed-size types (int8, int64), and demonstrates basic arithmetic operations.

Boolean Types

Booleans in Go are a distinct type `bool` with values `true` or `false`. This example covers logical operators (`&&`, `||`, `!`), short-circuit evaluation, and how booleans are used in control flow.

Byte Handling

Bytes are the fundamental unit of data in Go. This example explores the `byte` alias, `[]byte` slices for mutable data, and how to efficiently convert between strings and bytes using the `bytes` package.

If Expressions

Go's `if` statement is simple yet powerful. It supports an optional initialization statement that runs before the condition, allowing you to declare variables scoped strictly to the `if` block.

Switch Expressions

Go's `switch` statement is more flexible than C's. It handles multiple cases, supports expressions (not just constants), and eliminates implicit fallthrough. This example covers basic switches, multiple-value cases, and type switches.

For Loops

Go has only one looping construct: the `for` loop. However, it is versatile enough to act as a standard counter loop, a while loop, and an infinite loop. This example demonstrates all three patterns.

Range Iteration

The `range` keyword provides a clean way to iterate over slices, arrays, maps, strings, and channels. This example shows how to use `range` to access both indexes/keys and values.

Bitwise Operations

Go supports standard bitwise operators for low-level data manipulation. This example demonstrates AND, OR, XOR, bit shifting, and the unique "bit clear" (AND NOT) operator.

Custom Errors

Errors in Go are just values that implement the `error` interface. This example shows how to create custom error structs with additional context and how to use `errors.Is` and `errors.As` for robust error handling.

Arrays

Arrays in Go are fixed-size sequences of elements. Unlike slices, their size is part of their type. This example demonstrates array declaration, value semantics (copying), and 2D arrays.

Slices

Slices are the most common way to work with sequences of data in Go. Unlike arrays, they are dynamic. This example explains length vs. capacity, the `append` function, and how slices are actually "windows" into underlying arrays.

Maps

Maps are Go's built-in associative data type (hashes or dicts). This example covers creating maps, adding/deleting keys, checking for existence, and the random iteration order.

Structs

Structs are typed collections of fields. They are useful for grouping data together to form records. This example shows struct definition, initialization, pointers to structs, and anonymous structs.

Struct Tags

Struct tags allow you to attach metadata to struct fields. This is widely used by libraries like `encoding/json` to control serialization. This example shows how to define tags and access them using reflection.

Pointers

Pointers hold the memory address of a value. This example covers pointer declaration, dereferencing, the nil value, and how pointers interact with structs and functions.

Templates

Go has a powerful built-in template engine for generating text or HTML. This example shows how to parse templates, inject data, use actions like range/if, and execute them.

Anonymous Structs

Anonymous structs are one-off data structures defined without a name. They are perfect for temporary data grouping, table-driven tests, and unmarshaling complex JSON without polluting the global namespace.

Embedded Fields

Go uses struct embedding to achieve composition over inheritance. This example demonstrates how embedded fields work, method promotion, and how to access shadowed fields.

Tagged Struct Fields

Struct tags are metadata attached to fields, used heavily by libraries like `encoding/json` and `validator`. This example explores how to define custom tags and parse them using reflection.

Receiver Methods

Methods in Go can have either value or pointer receivers. This example explains the difference, when to use each, and how they affect the mutability of the receiver.

Make vs New

Go has two primitives for allocation: `make` and `new`. This example clarifies the difference: `new` allocates zeroed memory, while `make` initializes slices, maps, and channels.

Method Sets

Method sets determine which types satisfy an interface. This example explores the subtle rules governing why *T satisfies interfaces that T does not.

Time Formatting

Go uses a unique reference time (Mon Jan 2 15:04:05 MST 2006) for formatting. This example shows how to format dates and times using standard layouts and custom patterns.

Time Parsing

Parsing time strings converts them into `time.Time` objects. This example demonstrates `time.Parse` and handling errors with different layouts.

Time Duration Values

Durations represent the elapsed time between two instants. Go uses `int64` nanoseconds for high precision. This example covers arithmetic, constants, and parsing duration strings.

Int to String

Converting integers to strings is a common operation. The `strconv` package provides the most efficient way to do this.

String to Int

Parsing strings into integers requires handling potential errors. Go provides `Atoi` for simple cases and `ParseInt` for more control.

String to Float

Parsing floating-point numbers from strings is handled by `strconv.ParseFloat`. It supports both 32-bit and 64-bit precision.

Float to String

Converting floats to strings often requires controlling precision. `fmt.Sprintf` is convenient, while `strconv.FormatFloat` offers maximum control.

Check Empty String

Checking for empty strings is a frequent task. While `len(s) == 0` is valid, `s == ""` is often preferred for readability.

Compare Strings

Go strings are value types, so `==` works as expected. For case-insensitive comparison, `strings.EqualFold` is the most performant choice.

Split String

Splitting strings is handled by `strings.Split` for delimiters and `strings.Fields` for whitespace. Understanding the difference is key.

Join String

Concatenating strings efficiently is crucial. Use `strings.Join` for slices and `strings.Builder` for loops to avoid performance pitfalls.

Replace Text

Replacing substrings is simple with `strings.Replace` and `strings.ReplaceAll`.

Trim Spaces

Cleaning up user input often involves removing whitespace. `strings.TrimSpace` is the go-to tool.

Contains Substring

Checking if a string exists inside another is done with `strings.Contains`. For prefixes and suffixes, use `HasPrefix` and `HasSuffix`.

Random Number

Generating random numbers requires `math/rand`. Remember to seed the generator for varied results in older Go versions.

Embedding

Understand Struct Embedding, Go's mechanism for type composition. This example demonstrates how to embed one struct into another, promoting fields and methods to the outer struct and achieving inheritance-like behavior through composition.

Functions

Understand function declarations in Go. This example covers defining functions with parameters and return types, using the consecutive parameter syntax, and understanding functions as first-class citizens that can be passed around and returned.

Multiple Return Values

Learn about Multiple Return Values, a distinctive feature of Go. This example demonstrates how functions can return more than one value, a pattern commonly used for returning both a result and an error, and how to handle or ignore these return values.

Variadic Functions

Explore Variadic Functions in Go, which accept a variable number of arguments. This example shows how to define and call variadic functions, how to pass slices to them using the `...` syntax, and explains their common use cases like `fmt.Println`.

Closures

Understand Closures in Go, anonymous functions that can capture and maintain state from their surrounding scope. This example demonstrates how to create closures, how they isolate data, and their utility in functional programming patterns.

Pointers

Work with Pointers in Go to manage memory and pass references efficiently. This example contrasts pass-by-value with pass-by-reference, demonstrating how to declare pointers, dereference them to access values, and modify data in place.

Error Handling

Learn idiomatic Error Handling in Go. Unlike exception-based languages, Go treats errors as values. This example demonstrates the standard pattern of returning `(result, error)`, checking for non-nil errors, and defining custom error types for richer context.

Panic and Recover

Understand Panic and Recover, Go's mechanism for handling exceptional, unrecoverable errors. This example shows how to trigger a panic and how to use `defer` and `recover` to gracefully regain control of a panicking goroutine.

Defer Statements

Understand the `defer` keyword, used to schedule function calls to run after the surrounding function completes. This example demonstrates its LIFO execution order and its critical role in resource cleanup, such as closing files or unlocking mutexes.

Goroutines

Dive into Concurrency with Goroutines, Go's lightweight threads. This example demonstrates how to launch concurrent functions using the `go` keyword, explaining their non-blocking nature and how the Go runtime schedules them efficiently.

Channels

Understand Channels, the conduits that connect concurrent goroutines. This example demonstrates how to send and receive values to synchronize execution and share data safely without explicit locks, following Go's philosophy: "Do not communicate by sharing memory; instead, share memory by communicating."

Buffered Channels

Explore Buffered Channels in Go. Unlike unbuffered channels, buffered channels have a capacity and can accept values without a corresponding receiver up to a limit. This example shows how to create them and explains their non-blocking behavior when space is available.

Select Statements

Coordinate concurrency with the Select Statement, Go's control structure for waiting on multiple channel operations. This example demonstrates how to use `select` to handle asynchronous events, implement timeouts, and perform non-blocking channel operations.

Mutexes

Safely access shared state across multiple goroutines using mutual exclusion locks. This example demonstrates using `sync.Mutex` to prevent race conditions when incrementing a shared counter.

RWMutex

Optimize concurrent access with RWMutex (Read-Write Mutex). This example shows how to use `sync.RWMutex` to allow multiple concurrent readers while ensuring exclusive access for writers, a pattern that significantly improves performance for read-heavy workloads.

WaitGroups

Coordinate concurrent tasks using WaitGroups. This example demonstrates how to use `sync.WaitGroup` to wait for a collection of goroutines to finish executing, a fundamental pattern for synchronization in Go programs.

Worker Pools

Implement the Worker Pool pattern to manage concurrency and resources efficiently. This example shows how to dispatch jobs to a fixed number of worker goroutines using channels, preventing resource exhaustion and maximizing throughput.

Timers and Tickers

Handle time-based events with Timers and Tickers. This example covers `time.NewTimer` for one-off delays and `time.NewTicker` for recurring tasks, demonstrating how to integrate them with channels and select statements.

Context Cancellation

Understand Context Cancellation to manage long-running operations. This example demonstrates using the `context` package to propagate cancellation signals across goroutines, ensuring resources are released and work is stopped when it's no longer needed.

JSON Encoding

Work with JSON in Go using the `encoding/json` package. This example covers marshalling Go structs to JSON and unmarshalling JSON back into structs, including the use of struct tags to customize field names and handling complex data types.

XML Encoding

Handle XML data in Go with the `encoding/xml` package. This example demonstrates how to map nested XML structures to Go structs using tags, handle attributes vs. elements, and perform both encoding and decoding operations.

File Reading

Learn File I/O operations in Go. This comprehensive example demonstrates reading files entirely, reading in chunks, and processing line-by-line using `bufio`, as well as creating and writing data to files using the `os` package.

Directories

Learn to manipulate the filesystem with Go's `os` and `path/filepath` packages. This example covers creating directories, reading directory contents, checking file existence, and recursively walking directory trees.

HTTP Client

Perform HTTP requests in Go using the `net/http` package. This example demonstrates how to perform GET requests, set custom headers, parse response bodies, and properly manage resources by closing response bodies.

HTTP Server Basics

Learn to build a basic HTTP server in Go using the standard `net/http` package. This example shows how to register route handlers, process incoming requests, and send responses, forming the foundation for web development in Go.

Building REST APIs

Build a RESTful API in Go without external frameworks. This example demonstrates how to handle different HTTP methods (GET, POST), route requests, and work with JSON data using the standard library, providing a deep understanding of HTTP mechanics.

WebSockets

Implement real-time, bidirectional communication using WebSockets in Go. This example uses the robust `gorilla/websocket` library to create a simple echo server, demonstrating the upgrade process and message handling loop.

Command-line Arguments

Learn how to access and process raw command-line arguments in Go using `os.Args`. This example explains the structure of the arguments slice and how to distinguish between the program name and user-provided arguments.

Flags Package

Utilize Go's `flag` package to parse command-line flags. This example demonstrates how to define string, integer, and boolean flags, parse them, and access their values, enabling you to build configurable command-line tools.

Building CLI Tools with Cobra

Build professional-grade CLI applications using Cobra. This example introduces the Cobra library, used by projects like Kubernetes, showing how to define commands, subcommands, and flags with automatic help generation.

Configuration with Viper

Manage application configuration effectively with Viper. This example demonstrates how to read configuration from files (JSON, YAML, etc.), set defaults, and access values, providing a robust solution for 12-factor apps.

Logging with log Package

Explore Go's standard `log` package for application logging. This example covers basic logging, configuring output flags (timestamps, file names), and redirecting logs to files, suitable for simple applications and debugging.

Advanced Logging with Zap

Achieve high-performance structured logging with Uber's Zap library. This example compares the type-safe, zero-allocation `Logger` with the more convenient `SugaredLogger`, demonstrating how to log structured data efficiently.

Environment Variables

Learn how to interact with Environment Variables in Go. This example demonstrates setting, retrieving, and listing environment variables using the `os` package, a crucial skill for configuring applications across different environments.

Custom Middleware

Understand the Middleware pattern in Go web development. This example shows how to create custom middleware to wrap HTTP handlers, enabling cross-cutting concerns like logging, authentication, and error handling to be applied consistently.

Unit Testing

Learn Unit Testing with Go's built-in `testing` package. This example covers writing basic test functions, implementing table-driven tests for better coverage and maintainability, and running tests with the `go test` command.

Benchmarking

Measure and optimize code performance with Go's built-in Benchmarking tools. This example demonstrates how to write benchmark functions, interpret the results, and use them to make data-driven optimization decisions.

Test Coverage

Ensure code quality by measuring Test Coverage. This example explains how to use Go's testing tools to generate coverage reports, helping you identify untested code paths and improve the reliability of your application.

Mocking with Testify

Learn to mock dependencies in tests using the `testify` toolkit. This example demonstrates creating mock objects, setting expectations for method calls, and asserting behavior, allowing for isolated and deterministic unit tests.

Database Basics

Connect to and interact with SQL databases using Go's `database/sql` package. This example covers the generic interface for database operations, including opening connections, executing queries, and managing transactions safely.

Using MySQL

Connect to MySQL databases using the Go MySQL driver. This example provides specific details on constructing the Data Source Name (DSN) and configuring connection pooling parameters for optimal performance and stability.

Using PostgreSQL

Connect to PostgreSQL databases using the `lib/pq` driver. This example demonstrates the connection string format for PostgreSQL and shows how to verify the connection and execute basic queries.

ORM with GORM

Simplify database interactions with GORM, a developer-friendly ORM for Go. This example covers defining models, performing auto-migrations, and executing CRUD (Create, Read, Update, Delete) operations with a fluent API.

Building APIs with Gin

Build high-performance web APIs with the Gin framework. This example introduces Gin's routing capabilities, JSON response handling, and request binding, showcasing why it's a popular choice for modern Go web development.

Building APIs with Fiber

Create fast and scalable web applications with Fiber, an Express-inspired framework for Go. This example demonstrates Fiber's familiar API for routing and handling requests, making it an excellent choice for developers coming from Node.js.

Router Middleware in Gin

Implement custom middleware in Gin to intercept and process requests. This example demonstrates how to write middleware functions that can modify the request context, log data, or halt execution, providing granular control over the request lifecycle.

JWT Authentication

Secure your applications with JSON Web Tokens (JWT). This example demonstrates how to generate signed tokens with custom claims and validate incoming tokens using the `golang-jwt` package, a standard for stateless authentication.

Password Hashing

Protect user credentials by hashing passwords with bcrypt. This example shows how to securely hash passwords before storage and verify them during login, a critical security practice for any application handling user accounts.

Defer

Ensure function calls are performed later in a program's execution, usually for cleanup purposes. This example demonstrates the LIFO execution order of deferred calls and their common use cases.

Panic and Recover

Handle unexpected errors and prevent program crashes. This example shows how to trigger a panic and use `recover()` within a deferred function to regain control and handle the error gracefully.

WaitGroups

Synchronize concurrent operations by waiting for a collection of goroutines to finish. This example demonstrates using `sync.WaitGroup` to coordinate multiple workers.

Generics

Write flexible, reusable code that works with any data type using Generics (introduced in Go 1.18). This example shows how to define generic functions and types with type constraints.

Embed Directive

Embed static files and assets directly into your Go binary. This example demonstrates using the `//go:embed` directive to include files as strings, byte slices, or a virtual filesystem.

Lambda Handler Example

Learn how to write a basic AWS Lambda handler in Go. This example demonstrates the standard handler signature, event parsing, and returning responses using the `aws-lambda-go` SDK.

Invoke Lambda Function

Programmatically invoke other Lambda functions using the AWS SDK for Go v2. This sample shows how to configure the client, create a payload, and execute a synchronous invocation.

Serverless API with Lambda

Build a serverless REST API using AWS Lambda and API Gateway. This example demonstrates how to handle API Gateway Proxy events, parse HTTP requests, and return structured HTTP responses.

Upload File to S3

Upload files to Amazon S3 efficiently using the AWS SDK for Go v2. This example demonstrates using the `s3/manager` package to handle multipart uploads automatically for large files.

Download File from S3

Download files from Amazon S3 using the AWS SDK for Go v2. This example shows how to use the `s3/manager` Downloader to efficiently download objects to a local file.

List Objects in S3

List files and folders in an S3 bucket using the AWS SDK for Go v2. This example demonstrates how to use paginators to retrieve all objects in a bucket efficiently.

DynamoDB Put Item

Learn how to insert or replace items in an Amazon DynamoDB table using the AWS SDK for Go v2. This sample demonstrates how to marshal a Go struct into a DynamoDB item and execute the PutItem operation.

DynamoDB Get Item

Retrieve a single item from an Amazon DynamoDB table using its primary key. This sample shows how to use `GetItem` and unmarshal the result back into a Go struct.

DynamoDB Scan Table

Scan an entire DynamoDB table to retrieve all items. This sample demonstrates how to use the `Scan` operation with pagination to process large datasets efficiently.