Do formal parameters occupy memory in Go language?

WBOY
Release: 2024-04-04 08:27:01
Original
1064 people have browsed it

Go语言中,值类型的形参不会占用额外内存,而引用类型的形参会占用指向堆中实际数据的指针的大小。

Do formal parameters occupy memory in Go language?

Go 语言中形参是否占用内存

在 Go 语言中,形参是传递给函数的参数。对于值类型(int、float、string),形参存储在函数的栈帧中。对于引用类型(slice、map、channel),形参存储在函数栈帧中指向堆中实际数据的指针。

是否占用内存

形参是否占用内存取决于参数传递机制。Go 语言采用值传递机制,即形参是实参的副本。因此,值类型的形参不会占用额外的内存,而引用类型的形参会占用指向堆中实际数据的指针的大小。

实战案例:

以下代码演示了值类型和引用类型的形参内存占用情况:

package main

import "fmt"

func main() {
    // 值类型
    var a int = 100
    b := a // 赋值,b 是 a 的副本

    // 引用类型
    slice := []int{1, 2, 3}
    slc := slice // 赋值,slc 是 slice 的指针副本

    fmt.Printf("a: %d (栈)\n", a)
    fmt.Printf("b: %d (栈)\n", b)
    fmt.Printf("slice: %p (堆)\n", &slice)
    fmt.Printf("slc: %p (栈)\n", &slc)
}
Copy after login

输出结果:

a: 100 (栈)
b: 100 (栈)
slice: 0xc0000a8040 (堆)
slc: 0xc0000a8038 (栈)
Copy after login

从输出结果可以看出,值类型形参 b 存储在栈中,占用 4 字节的内存。引用类型形参 slc 也存储在栈中,占用 8 字节的内存,指向堆中实际数据的指针。

The above is the detailed content of Do formal parameters occupy memory in Go language?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!