10 Essential Go Practices for Robust, Maintainable Code

This article shares ten practical Go best‑practice tips—ranging from using a single GOPATH and structuring for‑select loops to defining custom types, adding String methods for enums, and wrapping repetitive logic with context functions—to help developers write flexible, readable, and error‑resistant Go programs.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
10 Essential Go Practices for Robust, Maintainable Code

These ten useful Go techniques are distilled from years of writing Go code and represent the author’s best‑practice recommendations. They aim to make applications adaptable, easy to extend, understandable by many developers, and simple to maintain, with bugs that are easy to discover and fix.

1. Use a single GOPATH

Multiple GOPATHs reduce flexibility and can cause versioning side‑effects; a single GOPATH simplifies dependency management and speeds up development.

2. Wrap for‑select in a function

When you need to break out of a for‑select loop, use a label; however, it is clearer to encapsulate the loop in its own function.

func main() {
L:
    for {
        select {
        case <-time.After(time.Second):
            fmt.Println("hello")
        default:
            break L
        }
    }
    fmt.Println("ending")
}

Encapsulating the loop:

func main() {
    foo()
    fmt.Println("ending")
}

func foo() {
    for {
        select {
        case <-time.After(time.Second):
            fmt.Println("hello")
        default:
            return
        }
    }
}

3. Initialise structs with field names (tag syntax)

Using named fields prevents compilation errors when the struct definition changes.

type T struct {
    Foo string
    Bar int
}

func main() {
    t := T{"example", 123} // without tags – fragile
    fmt.Printf("t %+v
", t)
}

With tags:

type T struct {
    Foo string
    Bar int
    Qux string
}

func main() {
    t := T{Foo: "example", Qux: 123}
    fmt.Printf("t %+v
", t)
}

4. Split struct initialisation across multiple lines

Multi‑line literals improve readability and make it easy to comment out or add fields.

T{Foo: "example", Bar: someLongVariable, Qux: anotherLongVariable, B: forgetToAddThisToo}
// better:
T{
    Foo: "example",
    Bar: someLongVariable,
    Qux: anotherLongVariable,
    B:   forgetToAddThisToo,
}

5. Add a String() method to integer constants

Define a custom enum type and implement String() so printed values are meaningful.

type State int

const (
    Running State = iota
    Stopped
    Rebooting
    Terminated
)

func main() {
    state := Running
    fmt.Println("state ", state) // prints "state 0"
}

After adding String():

func (s State) String() string {
    switch s {
    case Running:
        return "Running"
    case Stopped:
        return "Stopped"
    case Rebooting:
        return "Rebooting"
    case Terminated:
        return "Terminated"
    default:
        return "Unknown"
    }
}

6. Make iota start from +1

Starting iota at 1 avoids the zero‑value representing a valid state, making uninitialised values obvious.

const (
    Running State = iota + 1
    Stopped
    Rebooting
    Terminated
)

func main() {
    t := T{Name: "example", Port: 6666}
    fmt.Printf("t %+v
", t) // State will be "Unknown"
}

7. Return function calls directly

If a function simply forwards its return values, return the call itself.

func bar() (string, error) {
    v, err := foo()
    if err != nil {
        return "", err
    }
    return v, nil
}

// simplified
func bar() (string, error) {
    return foo()
}

8. Define slices and maps as custom types

Custom types make future extensions easier.

type Server struct { Name string }

func ListServers() []Server {
    return []Server{{Name: "Server1"}, {Name: "Server2"}, {Name: "Foo1"}, {Name: "Foo2"}}
}

func ListServers(name string) []Server {
    servers := []Server{{Name: "Server1"}, {Name: "Server2"}, {Name: "Foo1"}, {Name: "Foo2"}}
    if name == "" { return servers }
    filtered := make([]Server, 0)
    for _, s := range servers {
        if strings.Contains(s.Name, name) { filtered = append(filtered, s) }
    }
    return filtered
}

9. Wrap repetitive logic with a context function

Encapsulate common setup such as locking or acquiring a DB connection.

func withLockContext(fn func()) {
    mu.Lock()
    defer mu.Unlock()
    fn()
}

func foo() {
    withLockContext(func() {
        // foo work
    })
}

Database‑specific version:

func withDBContext(fn func(db DB) error) error {
    dbConn := NewDB()
    return fn(dbConn)
}

10. Add setters/getters for map access

Encapsulating map operations prevents race conditions and centralises synchronization.

func Put(key, value string) {
    mu.Lock()
    m[key] = value
    mu.Unlock()
}

func Delete(key string) {
    mu.Lock()
    delete(m, key)
    mu.Unlock()
}

Define an interface to hide implementation details:

type Storage interface {
    Delete(key string)
    Get(key string) string
    Put(key, value string)
}

Link: https://www.cnblogs.com/zhangboyu/p/7456651.html

(Copyright belongs to the original author, removed upon request)

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

GolangSoftware Engineeringcode quality
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.