go - 如何实现通用 slice 附加器?

标签 go reflection slice

<分区>

我对 go 比较陌生。我正在尝试编写一个通用的“appender”函数。这是一种简化,但它试图创建一个干净的界面来处理某些列表。具体来说,我对由此产生的两个错误有疑问:

package main

type GenericFunc func() *interface{}
func Append(ints interface{}, f GenericFunc) {
    ints = append(ints, f())
}

func ReturnInt() *int {
    i := 1
    return &i
}

func main() {
    var ints []*int
    Append(ints, ReturnInt)
}

Playground

prog.go:5:18: first argument to append must be slice; have interface {} prog.go:15:11: cannot use ReturnInt (type func() *int) as type GenericFunc in argument to Append

  1. 为什么 ReturnInt 不能是 GenericFunc 类型?如果这不起作用,我根本不明白 interface{} 是如何与函数一起使用的……可以吗?
  2. 如何接受“通用” slice 并使用反射附加到它?这将涉及检查 GenericFunc 是否返回与 slice 相同的类型,但在此之后附加应该是可能的。

最佳答案

类型func() *interface{}(GenericFunc的type类型)和(type func() *int)(ReturnInt的类型)是不同的类型.一个返回一个 *interface{}。另一个返回一个 *int。这些类型不能相互分配。

使用此函数一般将函数的结果附加到 slice :

func Append(sp interface{}, f interface{}) {
    s := reflect.ValueOf(sp).Elem()
    s.Set(reflect.Append(s, reflect.ValueOf(f).Call(nil)[0]))
}

这样调用它:

var ints []*int
Append(&ints, ReturnInt)

如果参数不是指向 slice 的指针,或者函数没有返回可分配给 slice 元素的值,则函数将出现 panic。

playground example

关于go - 如何实现通用 slice 附加器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51624639/

相关文章:

testing - Cobra:如何在测试中以编程方式设置标志

c# - MethodBase.GetCurrentMethod()反射线解释

python - 如何将 Pandas 列切片转置并插入到行切片中?

python - Pandas:当某些级别不匹配时,将一个多索引数据帧与另一个多索引数据帧进行切片

go - 在 Go 项目中初始化 git 的位置

json - 请帮我弄清楚如何解析这个json文件

go - 为什么 Go 根据我声明缓冲区的位置设置不同的内容类型

Java:NoSuchMethodException,即使该方法存在

c# - 我可以在运行时为 OrderBy 实例化一个 IComparer 类,而不考虑类型吗?

string - Go中如何将十六进制字符串直接转为[]byte?