Handle structured errors with
Use
#tip #code #errors
@golang_tips
errors.As
Use
errors.As
to extract specific error types from a chain for granular error handling.type NotFoundError struct{ Msg string }
func (e *NotFoundError) Error() string { return e.Msg }
err := fmt.Errorf("wrapped: %w", &NotFoundError{Msg: "User not found"})
var target *NotFoundError
if errors.As(err, &target) {
fmt.Println("Found:", target.Msg) // Output: Found: User not found
}
#tip #code #errors
@golang_tips
Propagate Context deadlines for cancellable workflows
Use
#tip #code
@golang_tips
Use
context.WithTimeout
to enforce deadlines in distributed systems or long-running operations.ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond)
defer cancel()
select {
case <-time.After(1 * time.Second):
fmt.Println("Task completed")
case <-ctx.Done():
fmt.Println("Deadline exceeded:", ctx.Err()) // Output: Deadline exceeded
}
#tip #code
@golang_tips
👍1
Advanced Custom Allocators with
The standard memory allocation in Go is efficient for most cases, but when working with high-performance systems, you might need a custom allocator. Using
#advanced #tip
@golang_tips
sync.Pool
and Memory ReuseThe standard memory allocation in Go is efficient for most cases, but when working with high-performance systems, you might need a custom allocator. Using
sync.Pool
intelligently can reduce GC pressure by reusing objects. Design your pools to handle not just homogeneous objects, but to recycle complex structures. This tip covers how to implement pooling strategies that go beyond common examples, tailoring object reuse for high-frequency, low-latency tasks.package main
import (
"fmt"
"sync"
)
type Buffer struct {
data []byte
}
var bufferPool = sync.Pool{
New: func() interface{} { return &Buffer{data: make([]byte, 1024)} },
}
func processData() {
buf := bufferPool.Get().(*Buffer)
// simulate usage
buf.data[0] = 42
fmt.Println("Buffer first byte:", buf.data[0])
// Reset state if needed before putting back
bufferPool.Put(buf)
}
func main() {
processData()
}
#advanced #tip
@golang_tips
Complex Reflection Techniques for Dynamic Type Manipulation
Go’s reflect package provides powerful tools to inspect and manipulate types at runtime. This tip explores advanced patterns where you modify unexported fields or dynamically instantiate types using reflection. By combining deep type introspection with careful error checking, you can implement frameworks that automatically map data or perform dependency injection—all while navigating Go’s type system and ensuring runtime safety.
#tip #advanced
@golang_tips
Go’s reflect package provides powerful tools to inspect and manipulate types at runtime. This tip explores advanced patterns where you modify unexported fields or dynamically instantiate types using reflection. By combining deep type introspection with careful error checking, you can implement frameworks that automatically map data or perform dependency injection—all while navigating Go’s type system and ensuring runtime safety.
package main
import (
"fmt"
"reflect"
)
type secret struct {
value int
}
func main() {
s := secret{value: 10}
v := reflect.ValueOf(&s).Elem()
field := v.FieldByName("value")
if field.CanSet() {
field.SetInt(42)
}
fmt.Printf("Modified secret: %+v\n", s)
}
#tip #advanced
@golang_tips
❤1
Slash
Slash is an open source, self-hosted platform designed to help you organize, manage, and share your most important links. Easily create customizable, human-readable shortcuts to streamline your link management. Use tags to categorize your links and share them easily with your team or publicly.
GitHub
#project #showcase
@golang_tips
Slash is an open source, self-hosted platform designed to help you organize, manage, and share your most important links. Easily create customizable, human-readable shortcuts to streamline your link management. Use tags to categorize your links and share them easily with your team or publicly.
GitHub
#project #showcase
@golang_tips
Memos
An open-source, self-hosted note-taking solution designed for seamless deployment and multi-platform access. Experience effortless plain text writing with pain-free, complemented by robust Markdown syntax support for enhanced formatting.
Features:
- Privacy First 🏡: Your data, your control. All runtime data is securely stored in your local database.
- Create at Speed ✍️: Write and save content as plain text for quick access, with Markdown support for fast formatting and easy sharing.
- Lightweight but Powerful ⚡️: Built with Go and React.js, our app combines a compact architecture with powerful performance.
- Customizable 🧩: Personalize your experience by customizing the server name, icon, description, theme, and execution scripts.
- Open Source 🦦: Fully open source, with all code available on GitHub for transparency and collaboration.
- Free to Use 💸: Enjoy all features at no cost, no hidden fees, no subscriptions
Website
GitHub
#project #showcase
@golang_tips
An open-source, self-hosted note-taking solution designed for seamless deployment and multi-platform access. Experience effortless plain text writing with pain-free, complemented by robust Markdown syntax support for enhanced formatting.
Features:
- Privacy First 🏡: Your data, your control. All runtime data is securely stored in your local database.
- Create at Speed ✍️: Write and save content as plain text for quick access, with Markdown support for fast formatting and easy sharing.
- Lightweight but Powerful ⚡️: Built with Go and React.js, our app combines a compact architecture with powerful performance.
- Customizable 🧩: Personalize your experience by customizing the server name, icon, description, theme, and execution scripts.
- Open Source 🦦: Fully open source, with all code available on GitHub for transparency and collaboration.
- Free to Use 💸: Enjoy all features at no cost, no hidden fees, no subscriptions
Website
GitHub
#project #showcase
@golang_tips
bot
A Go zero-dependencies telegram bot framework.
Simple
GitHub
#library #telegram
@golang_tips
A Go zero-dependencies telegram bot framework.
Simple
echo
example:package main
import (
"context"
"os"
"os/signal"
"github.com/go-telegram/bot"
"github.com/go-telegram/bot/models"
)
// Send any text message to the bot after the bot has been started
func main() {
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt)
defer cancel()
opts := []bot.Option{
bot.WithDefaultHandler(handler),
}
b, err := bot.New("YOUR_BOT_TOKEN_FROM_BOTFATHER", opts...)
if err != nil {
panic(err)
}
b.Start(ctx)
}
func handler(ctx context.Context, b *bot.Bot, update *models.Update) {
b.SendMessage(ctx, &bot.SendMessageParams{
ChatID: update.Message.Chat.ID,
Text: update.Message.Text,
})
}
GitHub
#library #telegram
@golang_tips
GitHub
GitHub - go-telegram/bot: Telegram Bot API Go framework
Telegram Bot API Go framework. Contribute to go-telegram/bot development by creating an account on GitHub.
Bubble Tea
The fun, functional and stateful way to build terminal apps. A Go framework based on The Elm Architecture. Bubble Tea is well-suited for simple and complex terminal applications, either inline, full-window, or a mix of both.
GitHub
#library #tui #gui
@golang_tips
The fun, functional and stateful way to build terminal apps. A Go framework based on The Elm Architecture. Bubble Tea is well-suited for simple and complex terminal applications, either inline, full-window, or a mix of both.
GitHub
#library #tui #gui
@golang_tips
guide.elm-lang.org
The Elm Architecture · An Introduction to Elm
Go 1.24.1 and 1.23.7 released
Official announce: https://groups.google.com/g/golang-announce/c/4t3lzH3I0eI/m/b42ImqrBAQAJ
Download: http://go.dev/dl/#go1.24.1
#update #go
@golang_tips
Official announce: https://groups.google.com/g/golang-announce/c/4t3lzH3I0eI/m/b42ImqrBAQAJ
Download: http://go.dev/dl/#go1.24.1
#update #go
@golang_tips
Cobra
Cobra is a library for creating powerful modern CLI applications.
Cobra is used in many Go projects such as Kubernetes, Hugo, and GitHub CLI to name a few.
Features:
- Easy subcommand-based CLIs: app server, app fetch, etc.
- Fully POSIX-compliant flags (including short & long versions)
- Nested subcommands
- Global, local and cascading flags
Intelligent suggestions (app srver... did you mean app server?)
- Automatic help generation for commands and flags
- Grouping help for subcommands
Automatic help flag recognition of -h, --help, etc.
- Automatically generated shell autocomplete for your application (bash, zsh, fish, powershell)
- Automatically generated man pages for your application
- Command aliases so you can change things without breaking them
- The flexibility to define your own help, usage, etc.
- Optional seamless integration with viper for 12-factor apps
GitHub
Website
#library #project #showcase #cli
@golang_tips
Cobra is a library for creating powerful modern CLI applications.
Cobra is used in many Go projects such as Kubernetes, Hugo, and GitHub CLI to name a few.
Features:
- Easy subcommand-based CLIs: app server, app fetch, etc.
- Fully POSIX-compliant flags (including short & long versions)
- Nested subcommands
- Global, local and cascading flags
Intelligent suggestions (app srver... did you mean app server?)
- Automatic help generation for commands and flags
- Grouping help for subcommands
Automatic help flag recognition of -h, --help, etc.
- Automatically generated shell autocomplete for your application (bash, zsh, fish, powershell)
- Automatically generated man pages for your application
- Command aliases so you can change things without breaking them
- The flexibility to define your own help, usage, etc.
- Optional seamless integration with viper for 12-factor apps
GitHub
Website
#library #project #showcase #cli
@golang_tips
Check that Interface value is equal to nil
If interface contains
prints
To correctly check if interface is equal to nil, you can write function, similar to
This function will work as expected.
#tip #example
@golang_tips
If interface contains
nil
, it can be not equal nil, e.g.func main() {
var x interface{}
var y *int = nil
x = y
if x != nil {
fmt.Println("x != nil") // <-- actual
} else {
fmt.Println("x == nil")
}
fmt.Println(x) } // x != nil // <nil>
prints
x != nil
<nil>
To correctly check if interface is equal to nil, you can write function, similar to
func IsNil(x interface{}) bool {
if x == nil {
return true
}
return reflect.ValueOf(x).IsNil()
}
This function will work as expected.
#tip #example
@golang_tips
new
vs make
Both
make()
and new()
are used for memory allocation. But make()
returns initialized type value, while new()
returns nil-pointer to type.a := new(chan int) // a has *chan int type
b := make(chan int) // b has chan int type
#tip #example
@golang_tips
A beginner-friendly guide to Go
It is comprehensive guide for those new to Go programming. The book takes readers from basics through more advanced concepts including:
- Core language fundamentals
- Working with interfaces
- Mastering goroutines and channels
- Writing effective tests and much more
Leanpub: https://leanpub.com/myfirstgobook
#book #learning
@golang_tips
It is comprehensive guide for those new to Go programming. The book takes readers from basics through more advanced concepts including:
- Core language fundamentals
- Working with interfaces
- Mastering goroutines and channels
- Writing effective tests and much more
Leanpub: https://leanpub.com/myfirstgobook
#book #learning
@golang_tips
Leanpub
My First Go Book
My First Go Book is the perfect starting point for anyone eager to learn Go programming. Whether you are a complete beginner or an experienced developer exploring a new language, this book will guide you through the fundamentals of Go with easy-to-follow…
Docker
Docker is a popular containerization software. And yes, it is written in Go! This fact allows Docker to be fast and efficient.
#showcase #fact
@golang_tips
Docker is a popular containerization software. And yes, it is written in Go! This fact allows Docker to be fast and efficient.
#showcase #fact
@golang_tips
Go's mascot
Go has it's official mascot - Gopher. It has long history and very cute.
#fact
@golang_tips
Go has it's official mascot - Gopher. It has long history and very cute.
#fact
@golang_tips
Glance
A self-hosted dashboard that puts all your feeds in one place.
GitHub
#showcase #project
@golang_tips
A self-hosted dashboard that puts all your feeds in one place.
GitHub
#showcase #project
@golang_tips
👍1
Go 1.24.2 and 1.23.8 were released!
These updates are minor and focusing on security updates.
Announce: https://groups.google.com/g/golang-announce/c/Y2uBTVKjBQk/m/cs_6qIK5BAAJ
Download: https://go.dev/dl/#go1.24.2
#update
@golang_tips
These updates are minor and focusing on security updates.
Announce: https://groups.google.com/g/golang-announce/c/Y2uBTVKjBQk/m/cs_6qIK5BAAJ
Download: https://go.dev/dl/#go1.24.2
#update
@golang_tips
if err != nil
will be with us!Go team said that there are no any syntax sugar for error handling.
https://go.dev/blog/error-syntax
#language
@golang_tips
go.dev
[ On | No ] syntactic support for error handling - The Go Programming Language
Go team plans around error handling support