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

Variable parameter function in golang

王林
Release: 2024-02-12 15:42:06
forward
566 people have browsed it

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)
}
Copy after login

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...)
Copy after login

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...)
Copy after login

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,
        },
    }
Copy after login

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!

Related labels:
source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template