golang的new函数
In Golang, to allocate memory, we have two built-in functions new() and make().
在Golang中,要分配内存,我们有两个内置函数new()和make() 。
1)new()函数 (1) new() function)
Memory returned by new() is zeroed.
new()返回的内存为零。
new() only returns pointers to initialized memory.
new()仅返回指向初始化内存的指针。
new() works for all the data types (except channel, map), and dynamically allocates space for a variable of that type and initialized it to zero value of that type and return a pointer to it.
new()适用于所有数据类型(通道,映射除外),并为该类型的变量动态分配空间,并将其初始化为该类型的零值并返回指向它的指针。
Example:
例:
result = new(int)
is equivalent to
相当于
var temp int // declare an int type variable
var result *int // declare a pointer to int
result = &temp
Example/program:
示例/程序:
There are three different ways to create a pointer that points to a zeroed structure value, each of which is equivalent:
有三种不同的方法可以创建指向零结构值的指针,每种方法都等效:
package main
import "fmt"
type Sum struct {
x_val int
y_val int
}
func main() {
// Allocate enough memory to store a Sum structure value
// and return a pointer to the value's address
var sum Sum
p := &sum
fmt.Println(p)
// Use a composite literal to perform
//allocation and return a pointer
// to the value's address
p = &Sum{}
fmt.Println(p)
// Use the new function to perform allocation,
//which will return a pointer to the value's address.
p = new(Sum)
fmt.Println(p)
}
Output
输出量
&{0 0}
&{0 0}
&{0 0}
2)make()函数 (2) make() function)
make() only makes slices, maps, and channels. make returns value of type T(data type) not *T
Example of slices:
make([]int, 10, 20) – Here, make creates the slice, and initialize its content depending on the default data type value. here int is used, so the default value is 0.
new([20]int)[0:10] – Here, It will also create slice but returns pointers to initialized memory.
Example/program:
There are two different ways to initialize a map which maps string keys to bool values are given below.
package main
import "fmt"
func main() {
// Using make() to initialize a map.
m := make(map[string]bool, 0)
fmt.Println(m)
// Using a composite literal to initialize a map.
m = map[string]bool{}
fmt.Println(m)
}
Output
Reference: allocation_new
make()仅制作切片,地图和通道。 make返回类型T (数据类型)的值,而不是* T
切片示例:
make([] int,10,20) –在这里,make创建切片,并根据默认数据类型值初始化其内容。 这里使用int,所以默认值为0。
new([20] int)[0:10] –在这里,它还将创建切片,但返回指向已初始化内存的指针。
示例/程序:
有两种不同的初始化映射的方法,将字符串键映射到bool值的方法如下。
package main
import "fmt"
func main() {
// Using make() to initialize a map.
m := make ( map [ string ] bool , 0 )
fmt.Println(m)
// Using a composite literal to initialize a map.
m = map [ string ] bool {}
fmt.Println(m)
}
输出量
参考: allocation_new
最佳面试编码问题/挑战
翻译自: https://www.includehelp.com/golang/new-and-make-functions-with-examples.aspx
golang的new函数