douchungu0859 2014-07-18 11:55
浏览 29
已采纳

将切片从功能参数追加到切片

I am trying to find out, how slice works. Look at the following code

package main

import "fmt"

type ByteSlice []byte

func (p *ByteSlice) Append(data []byte) {
    slice := *p
    *p = append(slice, data...)
}

func main() {
    var a ByteSlice
    a[0] = 3
    b := []byte{4,6,7}
    a.Append(b)
    fmt.Println(b)
}

As you can see in the append function, i try to append slice parameter into call but i've got the following error:

panic: runtime error: index out of range

goroutine 16 [running]:
runtime.panic(0x4a14e0, 0x51333c)
    c:/go/src/pkg/runtime/panic.c:279 +0xe9
main.main()
    D:/Go/samples/src/method.go:16 +0x243

goroutine 17 [runnable]:
runtime.MHeap_Scavenger()
    c:/go/src/pkg/runtime/mheap.c:507
runtime.goexit()
    c:/go/src/pkg/runtime/proc.c:1445

goroutine 18 [runnable]:
bgsweep()
    c:/go/src/pkg/runtime/mgc0.c:1976
runtime.goexit()
    c:/go/src/pkg/runtime/proc.c:1445

goroutine 19 [runnable]:
runfinq()
    c:/go/src/pkg/runtime/mgc0.c:2606
runtime.goexit()
    c:/go/src/pkg/runtime/proc.c:1445
exit status 2

What do i here wrong?

  • 写回答

2条回答 默认 最新

  • dpg76975 2014-07-18 12:01
    关注

    See my comments line by line:

    a slice is just a "view" of an array.

    https://play.golang.org/p/gPppMHZncn

    package main
    
    import "fmt"
    
    type ByteSlice []byte
    
    func (p *ByteSlice) Append(data []byte) {
        *p = append(*p, data...)
    }
    
    func main() {
        var a ByteSlice // is just a pointer
        // a[0] = 3  does not have memory allocate
        a = append(a, 3) // append allocates a memory underneath
        fmt.Println(a[0])
        b := []byte{4, 6, 7}
        a.Append(b)
        fmt.Println(a)
    }
    

    output

    3 [3 4 6 7]

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog