在高朗切片杂耍

To be short, here is a deal:
http://play.golang.org/p/ePiZcFfPZP


If I use commented lines, everything works, but there is no
any control on allocation sizes (cap), so the slices,
if I got it correct, realloc every time they exceed their limit
and moreover, they start with zero capacity.

Passing a reference of newSlice in setSlice() don't work too.

So, I need ideomatic, elegant, go-ish method to do the job.


Thanks in advance, at least for attention and your time.

UPD: solution was to make SLICE and STASH *[]byte typed
and make assigns to them like:
var slicePtr *[]byte
tmp := make([]byte, 256)
slicePtr = &tmp // Tmp is needed because we can't take adress of make() rval.

For example,

package main

import "fmt"

var SLICE, STASH []byte

func init() {
    SLICE = make([]byte, 0, 5)
}

func setSlice(slice []byte) {
    STASH = SLICE
    SLICE = slice
}

func restoreSlice() {
    SLICE = STASH
}

func appendToSlice(parts ...byte) []byte {
    SLICE = append(SLICE, parts...)
    return SLICE
}

func main() {
    appendToSlice('f', 'o', 'o')
    fmt.Printf("Everything is fine: {'%s'}
", SLICE)

    newSlice := make([]byte, 0, 5)
    setSlice(newSlice)

    newSlice = appendToSlice('b', 'a', 'r')
    fmt.Printf("Bar? No! {'%s'}
", newSlice) // <- I need "bar" appear in newSlice.
    fmt.Printf("Bar is here: {'%s'}
", SLICE)

    restoreSlice()
    fmt.Printf("Back to origin. {'%s'}
", SLICE)
}

Output:

Everything is fine: {'foo'}
Bar? No! {'bar'}
Bar is here: {'bar'}
Back to origin. {'foo'}

Like the Go append built-in function, your appendToSlice function needs to return the result of the append.

func appendToSlice(parts ...byte) []byte {
    SLICE = append(SLICE, parts...)
    return SLICE
}

and

newSlice = appendToSlice('b', 'a', 'r')

The Go Programming Language Specification

Appending to and copying slices

The built-in functions append and copy assist in common slice operations. For both functions, the result is independent of whether the memory referenced by the arguments overlaps.

The variadic function append appends zero or more values x to s of type S, which must be a slice type, and returns the resulting slice, also of type S.

If the capacity of s is not large enough to fit the additional values, append allocates a new, sufficiently large underlying array that fits both the existing slice elements and the additional values. Otherwise, append re-uses the underlying array.

Example:

var b []byte
b = append(b, "bar"...)    // append string contents; b == []byte{'b', 'a', 'r' }