pointers - golang 中的 slice 杂耍

标签 pointers go slice

简而言之,这是一笔交易:
http://play.golang.org/p/ePiZcFfPZP


如果我使用注释行,一切正常,但没有
对分配大小 (cap) 的任何控制,因此 slice ,
如果我做对了,每次超过限制时重新分配
而且,它们从零容量开始。

setSlice() 中传递 newSlice 的引用也不起作用。

所以,我需要理想的、优雅的、随心所欲的方法来完成这项工作。


在此先感谢您的关注和您的时间。

更新: 解决方案是制作 SLICESTASH *[]byte typed
并像这样给他们分配:

var slicePtr *[]byte
tmp := make([]byte, 256)
slicePtr = &tmp // Tmp is needed because we can't take adress of make() rval.

最佳答案

例如,

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'}\n", SLICE)

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

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

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

输出:

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

与 Go 的 append 内置函数一样,您的 appendToSlice 函数需要返回追加的结果。

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

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' }

关于pointers - golang 中的 slice 杂耍,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25715193/

相关文章:

c# - 无法获取托管类型的地址、获取其大小或声明指向托管类型的指针

c - 我是否创建一个临时 c 结构并通过套接字发送它?

go - 为什么 -count=1 在 Go 测试中忽略缓存?

arrays - 将大数组拆分为两个元素的数组

python - 在 Pandas 数据框中,如何提取同一列中不同行的值之间的差异,以第二列为条件?

ruby - 元素到达时切片数组

c++ - 函数指针的静态初始化

c - 双指针获取导致段错误的字符串

compilation - 编译时按架构排除 go 源文件

go - 如何与 Golang 共享内存?