为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
德玛西亚99 2022-07-18 15:42:29
这是 Python 示例:s = ["push", "pop"] * 10如何在 Go 中做到这一点?
查看完整描述

1 回答

?
慕丝7291255

TA贡献1859条经验 获得超6个赞

乘以 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]



查看完整回答
反对 回复 2022-07-18
  • 1 回答
  • 0 关注
  • 115 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号