首页 > 解决方案 > Go 中的 slice 可以像 Python 的 list 一样成倍增加吗?

问题描述

这是 Python 示例:

s = ["push", "pop"] * 10

如何在 Go 中做到这一点?

标签: pythongo

解决方案


乘以 for 循环。没有内置任何东西。

in := []string{"push", "pop"}

n := 10
out := make([]string, 0, len(in)*n) // allocate space for the entire result
for i := 0; i < n; i++ {            // for each repetition...
    out = append(out, in...)        // append, append, ....
}

fmt.Println(out) // prints [push pop push pop push pop push pop push pop push pop push pop push pop push pop push pop]

使用反射包编写通用乘法器:

// multiply repeats the slice src n times to the slice pointed to by destiny.
func multiply(src interface{}, n int, dstp interface{}) {
    srcv := reflect.ValueOf(src)
    result := reflect.MakeSlice(srcv.Type(), 0, srcv.Len()*n)
    for i := 0; i < n; i++ {
        result = reflect.AppendSlice(result, srcv)
    }
    reflect.ValueOf(dstp).Elem().Set(result)
}

in := []string{"push", "pop"}
var out []string
repeat(in, 10, &out)

fmt.Println(out) // prints [push pop push pop push pop push pop push pop push pop push pop push pop push pop push pop]

推荐阅读