Go闭包如何布置在内存中? [英] How are Go closures layed out in memory?

查看:200
本文介绍了Go闭包如何布置在内存中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有关闭包的一般说明,请参见 JavaScript闭包如何工作?

Go闭包在内存中的位置如何?

How exactly are Go closures laid out in memory?

例如,以下函数:

type M int

func (m *M) Adder(amount int) func() {
    return func() {
        *m = *m + amount
    }
}

当我们的代码调用 a:= m.Adder()时,堆上分配了多少内存,并且它是什么样子的?返回的 func()值占用多少内存(无论在内存中的什么地方最终都会被占用)?

When our code calls a := m.Adder(), how much memory is allocated on the heap and what does it look like? How much memory does the returned func() value take up (wherever in memory it ends up being)?

推荐答案


Go编程语言
规范

函数文字

函数文字代表匿名函数。

A function literal represents an anonymous function.

FunctionLit = func签名FunctionBody。

func(a,b int,z float64)bool {return a * b< int(z)}

可以将函数文字分配给变量或直接调用。

A function literal can be assigned to a variable or invoked directly.

f := func(x, y int) int { return x + y }
func(ch chan int) { ch <- ACK }(replyChan)

函数文字是闭包的:它们可以引用在
a周围函数中定义的变量。然后,这些变量在
周围函数和函数文字之间共享,并且只要它们可访问,它们就以
生存。

Function literals are closures: they may refer to variables defined in a surrounding function. Those variables are then shared between the surrounding function and the function literal, and they survive as long as they are accessible.








闭包可能引用
a周围函数中定义的变量。然后,这些变量在
周围函数和函数文字之间共享,并且只要它们可访问,它们就以
生存。

Closures may refer to variables defined in a surrounding function. Those variables are then shared between the surrounding function and the function literal, and they survive as long as they are accessible.

可以在函数调用后保留的变量放在堆中。在Go中,关闭实际上就是这么简单。

Variables that survive a function call are put on the heap. In Go, closures are really that simple.

例如,

func closure() func() *byte {
    var b [4 * 1024]byte
    return func() *byte {
        return &b[0]
    }
}

A closure()调用是两个堆分配,一个分配给16个字节(在amd64上等于8 + 8)字节

A closure() call is two heap allocations, one for 16 (= 8 + 8 on amd64) bytes

struct { F uintptr; b *[4096]byte }

和一个4096字节

[4096]byte

总共4112个字节。

这篇关于Go闭包如何布置在内存中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆