英文:
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)
}
在使用Go语言的可变函数时,我有一个问题。
当将实现了接口的结构体作为参数传递时,可以进行单独的声明,但是为什么通过...
传递时不可行呢?
在下面的代码中会出现错误。
variadicExample2(impls...)
我阅读了这篇文章:
我发现上面的代码是可行的。
var impls []ISum
impls = append(impls, impl1)
impls = append(impls, impl1)
variadicExample2(impls...)
英文:
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
var impls []ISum
impls = append(impls, impl1)
impls = append(impls, impl1)
variadicExample2(impls...)
I found that the above code is possible.
答案1
得分: 4
一个 SumImpl
切片不是一个 ISum
切片。一个是结构体切片,另一个是接口切片。这就是为什么你不能将它传递给需要 []ISum
(即 ...ISUm
)的函数。
但你可以这样做:
impls := []ISum{
SumImpl{
Num: 1,
},
SumImpl{
Num: 2,
},
}
英文:
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,
},
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论