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

如何在切片增长时自动将切片的新元素添加到函数参数

如何在切片增长时自动将切片的新元素添加到函数参数

Go
三国纷争 2023-03-21 10:39:28
有没有办法自动执行此操作?package mainimport "fmt"func main() {    var a []string    a = append(a, "this", "this2", "this3")    increaseArguments(a)    a = append(a, "this4")    increaseArguments(a)}func increaseArguments(b []string) {    // I want, when i add new element to slice i want this function act as this    // fmt.Println(b[0],b[1], b[2], b[3])    fmt.Println(b[0], b[1], b[2])}除了将 b[3] 作为参数添加到 fmt.Println 之外,有没有办法自动添加它?
查看完整描述

1 回答

?
拉风的咖菲猫

TA贡献1995条经验 获得超2个赞

请注意,如果b是 type []any,您可以将其作为 的可变参数的值传递fmt.Println()

fmt.Println(b...)

但由于b是 type []string,你不能。

但是如果你变成b一个[]any切片,你可以。您可以使用此辅助函数来执行此操作:

func convert[T any](x []T) []any {

    r := make([]any, len(x))

    for i, v := range x {

        r[i] = v

    }

    return r

}

进而:


func increaseArguments(b []string) {

    fmt.Println(convert(b)...)

}

这将输出(在Go Playground上尝试):


this this2 this3

this this2 this3 this4

注意:在中创建新切片convert()不会使此解决方案变慢,因为显式传递值(如fmt.Println(b[0], b[1], b[2]))也会隐式创建切片。


查看完整回答
反对 回复 2023-03-21
  • 1 回答
  • 0 关注
  • 105 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信