dongsiju1941 2017-07-23 20:14
浏览 29
已采纳

就地更改函数内部的切片内容和容量

I am trying to learn Go, so here is my very simple function for removing adjacent duplicates from slice for exercise from the book by Donovan & Kernighan.
Here is the code: https://play.golang.org/p/avHc1ixfck

package main
import "fmt"

func main() {
    a := []int{0, 1, 1, 3, 3, 3}
    removeDup(a)
    fmt.Println(a)
}

func removeDup(s []int) {
    n := len(s)
    tmp := make([]int, 0, n)
    tmp = append(tmp, s[0])
    j := 1
    for i := 1; i < n; i++ {
        if s[i] != s[i-1] {
            tmp = append(tmp, s[i])
            j++
        }
    }
    s = s[:len(tmp)]
    copy(s, tmp)
}

It should print out [0 1 3] - and I checked, actually tmp at the end of the function it has desired form. However, the result is [0 1 3 3 3 3]. I guess there is something with copy function.

Can I somehow replace input slice s with the temp or trim it to desired length?

  • 写回答

2条回答 默认 最新

  • doumei1772 2017-07-23 20:54
    关注

    Option 1

    Return a new slice as suggested by @zerkms.
    https://play.golang.org/p/uGJiD3WApS

    package main
    import "fmt"
    
    func main() {
        a := []int{0, 1, 1, 3, 3, 3}
        a = removeDup(a)
        fmt.Println(a)
    }
    
    func removeDup(s []int) []int {
        n := len(s)
        tmp := make([]int, 0, n)
        tmp = append(tmp, s[0])
        for i := 1; i < n; i++ {
            if s[i] != s[i-1] {
                tmp = append(tmp, s[i])
            }
        }
        return tmp
    }
    

    Option 2
    Use pointers for pass-by-reference.
    The same thing in effect as that of option1.

    https://play.golang.org/p/80bE5Qkuuj

    package main
    
    import "fmt"
    
    func main() {
        a := []int{0, 1, 1, 3, 3, 3}
        removeDup(&a)
        fmt.Println(a)
    }
    
    func removeDup(sp *[]int) {
        s := *sp
        n := len(s)
        tmp := make([]int, 0, n)
        tmp = append(tmp, s[0])
        for i := 1; i < n; i++ {
            if s[i] != s[i-1] {
                tmp = append(tmp, s[i])
            }
        }
        *sp = tmp
    }
    

    Also, refer to following SO thread: Does Go have no real way to shrink a slice? Is that an issue?

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

报告相同问题?

悬赏问题

  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗
  • ¥15 钢筋实图交点识别,机器视觉代码
  • ¥15 如何在Linux系统中,但是在window系统上idea里面可以正常运行?(相关搜索:jar包)
  • ¥50 400g qsfp 光模块iphy方案
  • ¥15 两块ADC0804用proteus仿真时,出现异常