Go Notebook
  • Introduction
  • Syntax Helpers
    • Append
    • String
    • Slice
  • Idioms
    • Custom JSON Marshaling
    • Functional Options
    • Type Embedding
    • Laws of Reflection
  • Design Patterns
    • Builder
    • Factory Method
    • Object Pool
    • Singleton
    • Observer
    • Strategy
  • Hello World
    • Getting Started With Go
    • Go Packages
    • Hello World
  • Tic Tac Toe
    • Go Interfaces
    • Go Error Handling
    • Tic Tac Toe
  • HTTP Server
    • HTTP Handler
    • Build a Calculator
    • HTTP Unit Test
  • Concurrency
    • Goroutines
    • Go Concurrency Part 1
    • Go Concurrency Part 2
  • WebSocket Server
    • WebSocket Handler
    • Build a Chatroom
  • User Authentication
    • Go Module
    • Popular Web Libraries
    • React Tools
    • Build an Authentication Server
  • Numerical Computing
    • Gonum
    • Neural Networks
Powered by GitBook
On this page
  • Add/Remove from Middle
  • Performance Consideration
  • Sort
  1. Syntax Helpers

Slice

Add/Remove from Middle

Remove an element from the middle of a slice.

i := 1
s := append(s[:i], s[i+1:]...)

Performance Consideration

The builtin append() needs to create a new backing array if the capacity of the destination slice is less than what the length of the slice would be after the append. This also requires to copy the current elements from destination to the newly allocated array, so there are much overhead.

Sort

I can use Golang's sort package but my data type must implement the sort interface.

type Edge struct {
    Nodes  [2]*Node
    Weight int
}

// ByWeight implements Golang sort interface.
type ByWeight []*Edge

func (s ByWeight) Len() int {
    return len(s)
}

func (s ByWeight) Less(i, j int) bool {
    return s[i].Weight < s[j].Weight
}

func (s ByWeight) Swap(i, j int) {
    s[i], s[j] = s[j], s[i]
}
PreviousStringNextIdioms

Last updated 4 years ago