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

Time:11-29

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 ?

CodePudding user response:

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: How to pass multiple return values to a variadic function?

  • Related