Go Closures: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
No edit summary
No edit summary
 
(12 intermediate revisions by the same user not shown)
Line 1: Line 1:
=Internal=
=TO DEPLETE=


<font color=darkkhaki>
==Internal==
* [[Go Concepts - Functions#Closures|Functions]]
* [[Go Concepts - Functions#Closures|Functions]]
* [[Closures]]


=Overview=
==Overview==


A closure is an anonymous function declared within a block. The function has access to the local variables for the duration of its life.
A closure is an [[Go Concepts - Functions#Anonymous_Functions|anonymous functions]] declared within a block - and implicitly, within another function. The function continues to have access to the local variables it had access when it was created for the duration of its life. The function isn't given a copy of this variables, it has direct access to the ''same'' variables declared in the scope of the outer function: if the value of the variable changes in the outer function, that is reflected in the inner function. The function together with the non local variables it references is known as a ''closure''.


<pre>
<pre>
Line 14: Line 18:
}
}


s := []int {1, 2, 3, 4, 5, 6}
s := []int {1, 2, 3, 4, 5}


for _, value := range s {
for _, value := range s {
Line 21: Line 25:
</pre>
</pre>


More about closures is available [[Programming#Closures|here]].
Alternatively, the function literal and invocation can be defined in-line:
 
<pre>
inClosuresScope := 10
 
s := []int {1, 2, 3, 4, 5}
 
for _, value := range s {
    func (i int) {
        inClosuresScope += i
    }(value);
}
</pre>
 
More about closures is available [[Programming_Languages_Concepts#Closures|here]].

Latest revision as of 22:50, 28 August 2023

TO DEPLETE

Internal

Overview

A closure is an anonymous functions declared within a block - and implicitly, within another function. The function continues to have access to the local variables it had access when it was created for the duration of its life. The function isn't given a copy of this variables, it has direct access to the same variables declared in the scope of the outer function: if the value of the variable changes in the outer function, that is reflected in the inner function. The function together with the non local variables it references is known as a closure.

inClosuresScope := 10

var c = func (i int) {
    inClosuresScope += i
}

s := []int {1, 2, 3, 4, 5}

for _, value := range s {
     c(value);
}

Alternatively, the function literal and invocation can be defined in-line:

inClosuresScope := 10

s := []int {1, 2, 3, 4, 5}

for _, value := range s {
     func (i int) {
         inClosuresScope += i
     }(value);
}

More about closures is available here.