Home  >  Article  >  Backend Development  >  Variable parameter function in golang

Variable parameter function in golang

王林
王林forward
2024-02-12 15:42:06535browse

Variable parameter function in golang

Question content

package main

import (
    "fmt"
)

type isum interface {
    sum() int
}

type sumimpl struct {
    num int
}

func (s sumimpl) sum() int {
    return s.num
}

func main() {

    nums := []int{1, 2}
    variadicexample1(nums...)

    impl1 := sumimpl{num: 1}
    impl2 := sumimpl{num: 2}

    variadicexample2(impl1, impl2)

    impls := []sumimpl{
        {
            num: 1,
        },
        {
            num: 2,
        },
    }
    variadicexample2(impls...)
}

func variadicexample1(nums ...int) {
    fmt.print(nums, " ")
    total := 0
    for _, num := range nums {
        total += num
    }
    fmt.println(total)
}

func variadicexample2(nums ...isum) {

    fmt.print(nums, " ")
    total := 0
    for _, num := range nums {
        total += num.sum()
    }
    fmt.println(total)
}

I encountered a problem when using variable functions in go language.

When passing a struct implementing an interface as a parameter, a separate declaration is possible, but can you tell me why this is not possible when it is passed via... ?

An error occurred in the following code.

variadicexample2(impls...)

I read this article

How to pass interface parameters to variadic functions in golang?

var impls []ISum
impls = append(impls, impl1)
impls = append(impls, impl1)
variadicExample2(impls...)

I found that the above code is ok.

Solution

sumimpl slices are not isum slices. One is a structure slice and the other is an interface slice. That's why you can't pass it to a function that expects []isum (i.e. ...isum).

But you can do this:

impls := []ISum{
        SumImpl{
            Num: 1,
        },
        SumImpl{
            Num: 2,
        },
    }

The above is the detailed content of Variable parameter function in golang. 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