英文:
Does Go allow to capture function invocation within anonymous function only once?
问题
为了使我的问题更加精确,我将介绍一个C++代码片段:
int findSomething(const std::vector<int>& v, int val) {
auto it = std::find(v.begin(), v.end(), val);
return it == v.end() ? 0 : *it;
}
bool useAsSomething(int val) {
return val != val;
}
int main() {
std::vector<int> vec = {1, 2, 3, 4, 5, 6};
auto lambda = [val = findSomething(vec, 5)] { // findSomething is invoked only once
return useAsSomething(val);
};
std::cout << lambda();
}
我想用Go做同样的事情:
vec = filterVec(vec, func(val int) bool {
return useAsSomething(findSomething(vec))
})
在这种情况下,findSomething
被调用了 len(vec)
次,但我不想重复调用它。是否可能只调用一次 findSomething
,而不需要在外部声明一个变量并进行捕获?
英文:
To make my question more precise I am going to introduce a C++ code snippet:
int findSomething(const std::vector<int>& v, int val) {
auto it = std::find(v.begin(), v.end(), val);
return it == v.end() ? 0 : *it;
}
bool useAsSomething(int val) {
return val != val;
}
int main() {
std::vector<int> vec = {1, 2, 3, 4, 5, 6};
auto lambda = [val = findSomething(vec, 5)] { // findSomething is invoked only once
return useAsSomething(val);
};
std::cout << lambda();
}
I would like to do the same with Go:
vec = filterVec(vec, func(val int) bool {
return useAsSomething(findSomething(vec))
})
In this case findSomething
is invoked as many as len(vec)
but I do not want to repeat the invocation. Is it possible to invoke findSomething
only once without declaring a variable outside with following capturing?
答案1
得分: 1
在Go语言中,没有显式的捕获语法。你需要在外部声明预先计算的变量,然后它可以被隐式捕获。
x := findSomething(vec)
vec = filterVec(vec, func(val int) bool {
return useAsSomething(x, val)
})
英文:
There is no explicit capture syntax in Go. You have to declare the pre-computed variable outside, then it can be captured implicitly.
x := findSomething(vec)
vec = filterVec(vec, func(val int) bool {
return useAsSomething(x, val)
})
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论