How to pass parameters to a function all rows of an array

Asked

Viewed 173 times

2

I need to pass all lines of an array as parameters of a function, but I can’t leave it dynamic...

What I want to leave dynamic

args = append(args, u.yy)
args = append(args, u.xx)
args = append(args, u.dd)
args = append(args, u.kk)

smt.Exec(args[0], args[0], args[3], args[4])

what I am doing

args = append(args, u.yy)
args = append(args, u.xx)
args = append(args, u.dd)
args = append(args, u.kk)

smt.Exec(args)
//ou
smt.Exec(args[:])

but it’s not working... Can you help me?

1 answer

2


Using variadic functions:

    package main

    import "fmt"

    // Here's a function that will take an arbitrary number
    // of `int`s as arguments.
    func sum(nums ...int) {
        fmt.Print(nums, " ")
        total := 0
        for _, num := range nums {
            total += num
        }
        fmt.Println(total)
    }

    func main() {

        // Variadic functions can be called in the usual way
        // with individual arguments.
        sum(1, 2)
        sum(1, 2, 3)

        // If you already have multiple args in a slice,
        // apply them to a variadic function using
        // `func(slice...)` like this.
        nums := []int{1, 2, 3, 4}
        sum(nums...)
    }

More information https://gobyexample.com/variadic-functions and https://blog.learngoprogramming.com/golang-variadic-funcs-how-to-patterns-369408f19085.

  • Thank you very much, it worked perfectly!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.