Home > database >  variadic function in golang
variadic function in golang

Time:01-02

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 have a question while using variable functions in go language.

When passing a struct that implements an interface as an argument, individual declarations are possible, but can you tell me why it is not possible when passing it through ...?

An error occurs in the code below.

variadicExample2(impls...)

I read this

How to pass an interface argument to a variadic function in Golang?

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

I found that the above code is possible.

CodePudding user response:

A SumImpl slice is not a ISum slice. One is a slice of structs, and the other is a slice of interfaces. That's why you cannot pass it to a function that requires a []ISum (i.e. ...ISUm).

But you can do this:

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