[英]How to pass a pointer to a slice of a specific interface in Go?
我想通过将指向特定接口切片的指针传递给函数来实现多态,并更新函数内部的切片。 它与interface{}
配合得很好
package main
import (
"fmt"
"strconv"
)
type valuer interface {
value() string
}
type myInt int
func (i myInt) value() string {
return strconv.Itoa(int(i))
}
func values(vals interface{}) {
res, ok := vals.(*[]myInt)
if !ok {
panic("wrong type")
}
*res = []myInt{1, 2, 3}
}
func main() {
var a []myInt
values(&a)
for _, b := range a {
fmt.Println(b.value())
}
}
但是,如果我尝试将interface{}
更改为指向特定接口切片的指针,则它不起作用:
package main
import (
"fmt"
"strconv"
)
type valuer interface {
value() string
}
type myInt int
func (i myInt) value() string {
return strconv.Itoa(int(i))
}
func values(vals *[]valuer) {
*vals = []myInt{1, 2, 3}
}
func main() {
var a []myInt
values(&a)
for _, b := range a {
fmt.Println(b.value())
}
}
返回错误
./prog.go:19:8: cannot use []myInt literal (type []myInt) as type []valuer in assignment
./prog.go:24:9: cannot use &a (type *[]myInt) as type *[]valuer in argument to values
我究竟做错了什么?
从@kostix 提供的见解中,我可以看到我不能同时保留两者——非空接口的限制和传递具体类型切片指针的简单性。 因此,如果我确实想将输出保留为非空接口的一部分,我可以改为执行以下操作:
package main
import (
"fmt"
"strconv"
)
type valuer interface {
value() string
}
type myInt int
func (i myInt) value() string {
return strconv.Itoa(int(i))
}
func values() []valuer {
res := make([]valuer, 3)
c := []myInt{1, 2, 3}
for i, v := range c {
res[i] = v
}
return res
}
func main() {
a := values()
for _, b := range a {
fmt.Println(b.value())
}
}
它将使 api 更易于使用,并允许输出具有非空接口的多态性。
这种方法给用户带来了一个不便,如果他们想使用接口未指定的具体类型的方法,他们将不得不“拆箱”切片的成员。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.