相关疑难解决方法(0)

Golang将一个项目附加到切片上

为什么切片a保持不变?是否append()产生一个新的片?

package main

import (
    "fmt"
)

var a = make([]int, 7, 8)

func Test(slice []int) {
    slice = append(slice, 100)
    fmt.Println(slice)
}

func main() {
    for i := 0; i < 7; i++ {
        a[i] = i
    }

    Test(a)
    fmt.Println(a)
}
Run Code Online (Sandbox Code Playgroud)

输出:

[0 1 2 3 4 5 6 100]
[0 1 2 3 4 5 6]
Run Code Online (Sandbox Code Playgroud)

go

65
推荐指数
5
解决办法
12万
查看次数

在Golang追加的大O.

go的内置append函数的复杂性是什么?使用字符串连接怎么样+

我想通过附加除了该元素之外的两个切片来从切片中删除元素,例如.http://play.golang.org/p/RIR5fXq-Sf

nums := []int{0, 1, 2, 3, 4, 5, 6, 7}
fmt.Println(append(nums[:4], nums[5:]...))

=> [0 1 2 3 5 6 7]
Run Code Online (Sandbox Code Playgroud)

http://golang.org/pkg/builtin/#append说如果目的地有足够的容量,那么那个切片就是resliced.我希望"reslicing"是一个恒定的时间操作.我也希望使用相同的字符串连接+.

complexity-theory append go slice

11
推荐指数
1
解决办法
4403
查看次数

Golang:附加切片或没有分配

append()当给定切片的容量不足时,Go的功能仅分配新的切片数据(另请参阅:https://stackoverflow.com/a/28143457/802833).这可能导致意外行为(至少对我来说是一个golang新手):

package main

import (
    "fmt"
)

func main() {

    a1 := make([][]int, 3)
    a2 := make([][]int, 3)
    b := [][]int{{1, 1, 1}, {2, 2, 2}, {3, 3, 3}}
    common1 := make([]int, 0)
    common2 := make([]int, 0, 12) // provide sufficient capacity
    common1 = append(common1, []int{10, 20}...)
    common2 = append(common2, []int{10, 20}...)

    idx := 0
    for _, k := range b {
        a1[idx] = append(common1, k...) // new slice is allocated
        a2[idx] = append(common2, k...) …
Run Code Online (Sandbox Code Playgroud)

append go slice

-4
推荐指数
1
解决办法
1983
查看次数

标签 统计

go ×3

append ×2

slice ×2

complexity-theory ×1