Created
July 5, 2020 03:56
-
-
Save itchyny/2b2d321c0373a542b73682b004d7ace4 to your computer and use it in GitHub Desktop.
Golang prepend implementation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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