Go语言是否允许在匿名函数中只捕获一次函数调用?

huangapple go评论68阅读模式
英文:

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&lt;int&gt;&amp; 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&lt;int&gt; vec = {1, 2, 3, 4, 5, 6};

    auto lambda = [val = findSomething(vec, 5)] { // findSomething is invoked only once
        return useAsSomething(val);
    };

    std::cout &lt;&lt; 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)
})

huangapple
  • 本文由 发表于 2021年10月29日 00:15:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/69757593.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定