~/Ten Efficient Go Techniques for Developers

Feb 18, 2023


Error Handling with Multiple Return Values

Go favors explicit error handling by returning error as a second value in functions, helping avoid exceptions.

1
2
3
4
val, err := strconv.Atoi("10")
if err != nil {
  // handle error
}

Goroutines for Concurrency

Go routines enable lightweight concurrent execution by prefixing a function call with go.

1
2
3
go func() {
  fmt.Println("Hello from goroutine")
}()

Channels for Safe Communication

Channels in Go provide safe communication between goroutines.

1
2
3
ch := make(chan int)
go func() { ch <- 100 }()
val := <-ch

Defer for Cleanup

Use defer to schedule a function call after the surrounding function returns, useful for resource management.

1
2
f, _ := os.Open("file.txt")
defer f.Close()

Using Interface and Type Assertion

Go enables flexible code via interfaces and type assertions.

1
2
var i interface{} = "hello"
s := i.(string)

Struct Embedding

Reuse code with struct embedding.

1
2
3
4
5
type Base struct { ID int }
type User struct {
  Base
  Name string
}

Slices and Capacity Optimization

Create slices with predefined capacity for efficiency. Details on slices.

1
s := make([]int, 0, 100)

Map Existence Check

Confirm key existence in maps.

1
2
3
4
val, ok := myMap["key"]
if ok {
  // key exists
}

Testing with Example Functions

Use Example functions for code and documentation tests.

1
2
3
4
func ExampleAdd() {
  fmt.Println(Add(1, 2))
  // Output: 3
}

Context for Cancellation

Pass context to enable timeouts and cancellation for goroutines.

1
2
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
Tags: [golang] [tips]