Golang new和make

1|0简述

new() 和 make() 都是用于动态分配内存的内建函数

2|0new()函数

官方文档如下:

// The new built-in function allocates memory. The first argument is a type, // not a value, and the value returned is a pointer to a newly // allocated zero value of that type. func new(Type) *Type
  1. 初始化指定类型分配内存空间,并返回该类型的零值
  2. 返回的值为指针类型
  3. 适用于所有的数据类型(除了channel、map)
    实例:
package main import "fmt" type People struct { name string age int } func main() { t_int := new(int) fmt.Println("t_int初始化值为:", *t_int) people := new(People) people.name = "hh" people.age = 18 fmt.Println(people) } // 结果 t_int初始化值为: 0 &{hh 18}

3|0make()函数

make()只能用于对channelslicemap类型对初始化
官方定义:

//The make built-in function allocates and initializes an object //of type slice, map, or chan (only). Like new, the first argument is // a type, not a value. Unlike new, make's return type is the same as // the type of its argument, not a pointer to it. func make(t Type, size ...IntegerType) Type
  1. make 是为channelslicemap类型分配内存和初始化的
  2. make返回的是指定类型的类型,因为channelslicemap本身就是引用类型
// slice a := make([]int, 2, 10) // map b := make(map[string]int) // channel c := make(chan int, 10)

4|0总结

new基本可以为所有类型分配内存和初始化
make函数只能为channelslicemap进行初始化,并返回指定类型的类型;但不是置为零值
new不常用;channelslicemap的初始化必须使用make


__EOF__

本文作者Linux程
本文链接https://www.cnblogs.com/chengjiawei/p/15850277.html
关于博主:评论和私信会在第一时间回复。或者直接私信我。
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角推荐一下。您的鼓励是博主的最大动力!
posted @   焦耳|程  阅读(39)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示