1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
| package main
import "fmt"
func adder() func(int) int {
sum := 0
return func(i int) int {
sum += i
return sum
}
}
func main() {
a := adder()
for i := 0; i < 10; i++ {
fmt.Println(a(i))
}
} |
package main
import "fmt"
func adder() func(int) int {
sum := 0
return func(i int) int {
sum += i
return sum
}
}
func main() {
a := adder()
for i := 0; i < 10; i++ {
fmt.Println(a(i))
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
<?php
function adder ()
{
$sum = 0;
$add = function($i)use(&$sum)
{
$sum += $i;
return $sum;
};
return $add;
}
$a = adder();
for($i=0;$i<10;$i++)
{
echo $a($i);
echo PHP_EOL;
} |
<?php
function adder ()
{
$sum = 0;
$add = function($i)use(&$sum)
{
$sum += $i;
return $sum;
};
return $add;
}
$a = adder();
for($i=0;$i<10;$i++)
{
echo $a($i);
echo PHP_EOL;
}
未经允许不得转载:开心乐窝-乐在其中 » golang和php闭包对比