Created
April 15, 2019 14:44
-
-
Save 5idu/48d3162b6696e7308c4fb14bcb95870d to your computer and use it in GitHub Desktop.
make和new区别
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
### make和new的区别 | |
```go | |
// 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 | |
``` | |
- `new`只接受一个参数,这个参数是一个类型,分配好内存后,返回一个指向该类型内存地址的指针。同时请注意它同时把分配的内存置为零,也就是类型的零值 | |
```go | |
func make(t Type, size ...IntegerType) Typ | |
``` | |
- `make`只用于chan、map以及切片的内存创建,而且它返回的类型就是这三个类型本身,而不是他们的指针类型,因为这三种类型就是引用类型,所以就没有必要返回他们的指针了 | |
### 二者异同 | |
- 二者都是内存的分配(堆上),但是`make`只用于`slice`、`map`以及`channel`的初始化(非零值);而`new`用于类型的内存分配,并且内存置为零值。所以在我们编写程序的时候,就可以根据自己的需要很好的选择了。 | |
- `make`返回的还是这三个引用类型本身;而`new`返回的是指向类型的指针。 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment