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 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化