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

huangapple go评论83阅读模式
英文:

How to add new elements of a slice automatically to function parameter as slice grows

问题

有没有一种自动添加的方法呢?

package main

import "fmt"

func main() {
    var a []string
    a = append(a, "this", "this2", "this3")
    increaseArguments(a)
    a = append(a, "this4")
    increaseArguments(a)

}

func increaseArguments(b []string) {
    // 我希望,当我向切片中添加新元素时,这个函数会自动执行以下操作
    // fmt.Println(b[0],b[1], b[2], b[3])

    fmt.Println(b[0], b[1], b[2], b[len(b)-1])

}

在不将b[3]作为参数添加到fmt.Println中的情况下,有没有一种自动添加的方法呢?

英文:

Is there a way to doing this automatically ?

package main

import "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])

}

Instead of adding b[3] as argument to fmt.Println is there a way to add it automatically ?

答案1

得分: 1

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

fmt.Println(b...)

但是,由于b的类型是[]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]))也会隐式创建一个切片。

参考相关问题:https://stackoverflow.com/questions/52653779/how-to-pass-multiple-return-values-to-a-variadic-function

英文:

Note that if b would be of type []any, you could pass it as the value of the variadic parameter of fmt.Println():

fmt.Println(b...)

But since b is of type []string, you can't.

But if you transform b into a []any slice, you can. You can use this helper function to do it:

func convert[T any](x []T) []any {
    r := make([]any, len(x))
    for i, v := range x {
        r[i] = v
    }
    return r
}

And then:

func increaseArguments(b []string) {
    fmt.Println(convert(b)...)
}

This will output (try it on the Go Playground):

this this2 this3
this this2 this3 this4

Note: creating a new slice in convert() will not make this solution any slower, because passing values explicitly (like fmt.Println(b[0], b[1], b[2])) also implicitly creates a slice.

See related question: https://stackoverflow.com/questions/52653779/how-to-pass-multiple-return-values-to-a-variadic-function

huangapple
  • 本文由 发表于 2022年11月28日 20:54:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/74600900.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定