Home >Backend Development >Golang >How to automatically add new elements of a slice to a function parameter as the slice grows

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

王林
王林forward
2024-02-15 18:00:11890browse

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

php editor Xiaoxin shares a practical technique, that is, how to automatically add new elements to function parameters when the slice (Slice) grows. Slices are a flexible data structure, but can present some challenges when used within function parameters. This article will introduce a concise method to automatically add new elements to function parameters as the slice grows by using variable parameters (Variadic Arguments) and the spread operator (Spread Operator). This technique can improve the readability and maintainability of the code. Let's learn it together!

Question content

Is there a way to automate this?

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

}

Is there a way to automatically add b[3] as a parameter to fmt.println?

Workaround

Please note that if b is of type []any, you can treat it as fmt. println():

fmt.println(b...)

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

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

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

Then:

func increasearguments(b []string) {
    fmt.println(convert(b)...)
}

This will output (try it on go playground):

this this2 this3
this this2 this3 this4

Note: Creating a new slice in convert() will not make this solution slower, as passing the value explicitly (like fmt.println(b[0], b[ 1], b[2]) ) implicitly creates a slice.

View related questions: How to pass the values ​​of multiple return value variable parameter functions?

The above is the detailed content of How to automatically add new elements of a slice to a function parameter as the slice grows. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete