# 9.2 Go 的逃逸分析

全局变量的内存区域毫无疑问需要分配到堆上，我们仅对函数的局部变量进行分析。

我们知道 Go 语言遵循 copy-by-value(按值拷贝) 规则, 即程序在赋值、传递函数的参数、以及返回值的过程中，会完全拷贝一份对应类型的数据，然后将拷贝传递给对方。例如如下代码：

```go
type Lang struct {
    Name string
}

func copyLang(arg Lang) (result Lang) {
    l := arg          // 以 arg 的内容重新创建一个 Lang 实例，并将新实例赋值给 l
    l.Name = "Golang" // 修改 l.Name 的属性不会改变 arg 中的内容

    defer func() {
        fmt.Printf("In copyLang: arg.Name: %s, l.Name: %s, result.Name: %s. Add: %p\n", arg.Name, l.Name, result.Name, &result)
    }()

    return l // 同理，此处复制一份 l 赋值给返回值 result
}

func main() {
    l1 := Lang{"Java"}

    fmt.Printf("In main before copyLang: l1.Name: %s\n", l1.Name)
    // 1. 此处复制一份 l1, 然后作为参数传递给函数 copyLang, 即使函数修改了参数的内部属性，也不会影响 l1
    // 2. 将函数 copyLang 的返回值变量 result 复制一份，赋值给 l3
    l3 := copyLang(l1)

    fmt.Printf("In main after copyLang: l1.Name: %s, l3.Name: %s\n", l1.Name, l3.Name)
}
```

特别指出的是：在 `l3 := copyLang(l1)` 语句中，函数的返回值变量 `result` 与 l3 也指向不同的内存区域。对于没有命名的函数返回值，编译器会为其生成一个内部变量名，例如对于代码：

```go
func copyLang(arg Lang) Lang {
    return arg
}
```

编译器处理之后的代码相当于：

```go
func copyLang(arg Lang) (r0 Lang) {
    return arg
}
```

因此效果是一样的。可以发现由于规则 copy-by-value, 上述代码中所涉及的所有局部变量都指向自己单独的内存区域。既然如此，那么局部变量怎么可能需要逃逸呢？答案是指针！例如如下代码：

```go
func copyLang(arg Lang) *Lang {
    l2 := arg

    return &l2
}
```

因为函数返回的是 l2 的指针，所以程序在拷贝时必须将其内存分配到堆上，否则会造成悬挂指针（[Dangling Pointer](https://en.wikipedia.org/wiki/Dangling_pointer)）问题。因此 Go 的逃逸分析都是围绕着指针展开的，其核心思路基于如下两点：

1. 指向栈上对象的指针不能分配到堆上
2. 指向栈上对象的指针，其生命周期不能长于该对象

换而言之，如果一个指针被分配到了堆上，那么其指向的对象一定要分配到堆上；如果一个指针的生命周期长于其指向的对象，那么该对象一定要分配到堆上。上例中返回值指针的生命周期长于 l2, 因此 l2 会逃逸到堆上。

&#x20;除此之外，为了避免栈过于庞大，编译器会直接将大对象分配到堆上。

> &#x20;当函数返回一个指针时，程序也会根据 copy-by-value 规则拷贝一个新的指针对象并返回，但这两个指针对象所指向的是同一块内存地址。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://gocompiler.shizhz.me/9.-golang-bian-yi-qi-tao-yi-fen-xi/9.2-go-de-tao-yi-fen-xi.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
