函数范围

问题描述

我有 20 多个返回结构体或 nil 的函数。我需要遍历所有这些,如果它们返回一个结构,我会将它附加到一个结构切片中。所以我想知道是否有办法遍历所有函数并在结果不为零时追加结果,因为检查每个函数的结果似乎是在浪费时间。谁能建议一种方法来做到这一点?也许是一个例子什么的。

解决方法

所以,我知道你在评论中得到了答案,但我还是想举个例子:

funcs := []func()*struct{Thing int}{
    func()*struct{Thing int}{return nil},func()*struct{Thing int}{
        newStruct := struct{Thing int}{Thing: 1}
        return &newStruct
    },}

sliceOfStructs := []struct{Thing int}{}
for _,f := range funcs {
    res := f()
    if res != nil {
        sliceOfStructs = append(sliceOfStructs,*res)
    }
}