Skip to content

Instantly share code, notes, and snippets.

@itchyny
Created July 5, 2020 03:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save itchyny/2b2d321c0373a542b73682b004d7ace4 to your computer and use it in GitHub Desktop.
Save itchyny/2b2d321c0373a542b73682b004d7ace4 to your computer and use it in GitHub Desktop.
Golang prepend implementation
type Xs struct {
xs []*X
idx int
}
func (xs *Xs) prepend(x *X) *Xs {
if xs.idx == 0 {
ys := make([]*X, (len(xs.xs)+1)*2)
xs.idx = len(xs.xs) + 1
copy(ys[xs.idx+1:], xs.xs)
ys[xs.idx] = x
xs.xs = ys
} else {
xs.idx--
xs.xs[xs.idx] = x
}
return xs
}
func (xs *Xs) slice() []*X {
return xs.xs[xs.idx:]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment