Go.Tips
12 subscribers
7 photos
15 links
Useful tips, libraries and information for Go (Golang) developers

Rust::Tips: @rust_code_tips
My GitHub: https://github.com/ankddev
Download Telegram
What is the zero value of a string in Go?
Anonymous Quiz
25%
"0"
0%
nil
75%
""
0%
0
Which keyword is used to declare a constant in Go?
Anonymous Quiz
25%
var
75%
const
0%
let
0%
define
0%
constant
Is it possible to have a global variable in Go?
Anonymous Quiz
100%
Yes
0%
No
Which built-in function can be used to allocate memory in Go?
Anonymous Quiz
67%
alloc
0%
malloc
33%
new
0%
mem
0%
all
What is the result of append([]int{}, 1) in Go?
Anonymous Quiz
0%
Runtime panic
50%
Compilation error
50%
[1]
0%
[]
What is the type of nil in Go?
Anonymous Quiz
0%
int
25%
string
0%
Any
50%
interface{}
25%
Undefined
What is the purpose of the fallthrough keyword in Go?
Anonymous Quiz
0%
Loop again
50%
Exit switch
0%
Skip cases
50%
Continue to next case
Use sync.Once for Lazy Initialization
Use sync.Once to ensure a function runs only once, even in concurrent scenarios. It's perfect for lazy initialization of shared resources.
var once sync.Once
func initResource() {
fmt.Println("Initialized")
}
once.Do(initResource)

#tip #sync
@golang_tips
Use time.After for Timeouts
Combine select with time.After to handle timeouts in goroutines effectively.
select {
case <-ch:
case <-time.After(time.Second):
fmt.Println("Timeout")
}

#goroutins #tip
@golang_tips
Robert Griesemer, Rob Pike, and Ken Thompson designed Go at Google in 2007.
#fact
@golang_tips
Use embed for Static Assets
Use the embed package to 📦 include static assets like HTML or CSS directly in your 📎 binary.
//go:embed index.html
var content embed.FS

#tip #code
@golang_tips
Use runtime.GOMAXPROCS for CPU Control
🛠 Adjust GOMAXPROCS to control the number of OS threads used by Go programs.
runtime.GOMAXPROCS(4)

#code #tip
@golang_tips
What is the result of closing a closed channel in Go?
Anonymous Quiz
50%
Nothing
50%
Panic
0%
Runtime error
0%
Channel reopen
0%
Compile error
What is the result of cap(nil) in Go?
Anonymous Quiz
100%
0
0%
1
0%
2
0%
Panic
0%
Compilation error
Handle structured errors with 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 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 sync.Pool and Memory Reuse
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 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.
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