Go 中的 slice 可以像 Python 的 list 一样成倍增加吗?

这是 Python 示例:

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

如何在 Go 中做到这一点?


德玛西亚99
浏览 116回答 1
1回答

慕丝7291255

乘以 for 循环。没有内置任何东西。in := []string{"push", "pop"}n := 10out := make([]string, 0, len(in)*n) // allocate space for the entire resultfor i := 0; i < n; i++ {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // for each repetition...&nbsp; &nbsp; out = append(out, in...)&nbsp; &nbsp; &nbsp; &nbsp; // 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{}) {&nbsp; &nbsp; srcv := reflect.ValueOf(src)&nbsp; &nbsp; result := reflect.MakeSlice(srcv.Type(), 0, srcv.Len()*n)&nbsp; &nbsp; for i := 0; i < n; i++ {&nbsp; &nbsp; &nbsp; &nbsp; result = reflect.AppendSlice(result, srcv)&nbsp; &nbsp; }&nbsp; &nbsp; reflect.ValueOf(dstp).Elem().Set(result)}in := []string{"push", "pop"}var out []stringrepeat(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]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go