Loops 功能范围
我有20多个函数返回struct或nil。我需要检查所有的结构,如果它们返回一个结构,我会将它附加到结构的一个片段中。因此,我想知道是否有一种方法可以迭代所有函数,并在结果不是nil时追加结果,因为检查每个函数的结果似乎是浪费时间。有人能提出一个方法吗?也许是一个例子什么的。所以,我知道你在评论中得到了答案,但我想我还是举个例子:Loops 功能范围,loops,go,func,Loops,Go,Func,我有20多个函数返回struct或nil。我需要检查所有的结构,如果它们返回一个结构,我会将它附加到结构的一个片段中。因此,我想知道是否有一种方法可以迭代所有函数,并在结果不是nil时追加结果,因为检查每个函数的结果似乎是浪费时间。有人能提出一个方法吗?也许是一个例子什么的。所以,我知道你在评论中得到了答案,但我想我还是举个例子: funcs := []func()*struct{Thing int}{ func()*struct{Thing int}{return 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)
}
}
您可以在一个切片中列出函数并对其进行迭代,然后调用每个函数。你试过什么?你有什么问题?哦,哇,我不知道我能做到。非常感谢。我现在应该好了。