Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

variadic function in golang

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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,
        },
    }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading