Home > Software design >  Does Go allow to capture function invocation within anonymous function only once?
Does Go allow to capture function invocation within anonymous function only once?

Time:11-01

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?

CodePudding user response:

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)
})
  •  Tags:  
  • go
  • Related