Golang面试make和new的用法

在golang中,make和new都分配内存,但是它们之间仍然存在一些差异。只有了解它们之间的差异,才能在适当的场合使用它们。

为福田等地区用户提供了全套网页设计制作服务,及福田网站建设行业解决方案。主营业务为网站设计、网站制作、福田网站设计,以传统方式定制建设网站,并提供域名空间备案等一条龙服务,秉承以专业、用心的态度为用户提供真诚的服务。我们深信只要达到每一位用户的要求,就会得到认可,从而选择与我们长期合作。这样,我们也可以走得更远!

简而言之,new只是分配内存,而不初始化内存;make分配并初始化内存。所谓的初始化就是给一个类型赋一个初始值,例如,字符为空,整数为0,逻辑值为false。

从Golang的官方文档的builtin(内置的软件包)中可以找到,make和new的用法。

官方文档的内置的软件包

new的使用介绍:

我们先来看看new的定义

 
 
 
  1. // The new built-in function allocates memory. The first argument is a type,
  2. // not a value, and the value returned is a pointer to a newly
  3. // allocated zero value of that type.
  4. //内建函数new分配内存。其第一个实参为类型,而非值。其返回值为指向该类型的新分配的零值的指针。
  5. func new(Type) *Type

可以看出,它的参数是一个类型,返回值是指向该类型的内存地址的指针,并且分配的内存将被设置为零,即该类型的零值,即字符为空,整数为0,逻辑值为false

看一些例子

 
 
 
  1. type P struct {
  2.         Name string
  3.         Age  int
  4.     }   var a *[2]int
  5.     var s *string
  6.     var b *bool
  7.     var i *int
  8.     var ps *P
  9.     a = new([2]int)
  10.     s = new(string)
  11.     b = new(bool)
  12.     i = new(int)
  13.     ps = new(P) //structure
  14.     fmt.Println(a, " ", *a)
  15.     fmt.Println(s, " ", *s)
  16.     fmt.Println(b, " ", *b)
  17.     fmt.Println(i, " ", *i)
  18.     fmt.Println(ps, " ", *ps)

输出如下:

 
 
 
  1. &[0 0]   [0 0]
  2. 0xc0000821e0   
  3. 0xc0000a409a   false
  4. 0xc0000a40b0   0
  5. &{ 0}   { 0}

上面基础类型,我们看一下slice, map and channel类型是如何操作的:

 
 
 
  1. //map 操作
  2.    var mp *map[string]string
  3.    mp = new(map[string]string)
  4.     //注释掉下面的行,new map 返回为nil,直接使用会panic
  5.    //*mp = make(map[string]string) // if this line is omitted, it will pan "Pan: assignment to entry in nil map"“
  6.    (*mp)["name"] = "lc"
  7.    fmt.Println((*mp)["name"])
  8.       // slice 操作    var ms *[]string
  9.    ms = new([]string)
  10.   // 注释掉下面的行访问的时候会下标超出范围    //*ms = make([]string,5) // if this line is deleted, it will "panic: runtime error: index out of range"
  11.    (*ms)[0] = "lc"
  12.    fmt.Println((*ms)[0]) 

从上面可以看出,silce,map,channel和其他类型是引用类型。当引用类型初始化为nil时,不能直接分配nil,也不能使用new来分配内存,还需要使用make来进行分配。

make的使用介绍:

我们看一下make的定义

 
 
 
  1. / /The make built-in function allocates and initializes an object of type
  2. // slice, map, or chan (only). Like new, the first argument is a type, not a
  3. // value. Unlike new, make's return type is the same as the type of its
  4. // argument, not a pointer to it. The specification of the result depends on
  5. // the type:
  6. //  Slice: The size specifies the length. The capacity of the slice is
  7. //  equal to its length. A second integer argument may be provided to
  8. //  specify a different capacity; it must be no smaller than the
  9. //  length. For example, make([]int, 0, 10) allocates an underlying array
  10. //  of size 10 and returns a slice of length 0 and capacity 10 that is
  11. //  backed by this underlying array.
  12. //  Map: An empty map is allocated with enough space to hold the
  13. //  specified number of elements. The size may be omitted, in which case
  14. //  a small starting size is allocated.
  15. //  Channel: The channel's buffer is initialized with the specified
  16. //  buffer capacity. If zero, or the size is omitted, the channel is
  17. //  unbuffered.
  18. //切片:size指定了其长度。该切片的容量等于其长度。切片支持第二个整数实参可用来指定不同的容量; 它必须不小于其长度,因此 make([]int, 0, 10) 会分配一个长度为0,容量为10的切片。
  19. //映射:初始分配的创建取决于size,但产生的映射长度为0。size可以省略,这种情况下就会分配一个小的起始大小。
  20. //通道:通道的缓存根据指定的缓存容量初始化。若 size为零或被省略,该信道即为无缓存的。
  21. func make(t Type, size ...IntegerType) Type

可以看出,它返回的是类型本身而不是指针类型,因为make只能为slice,map,channel等初始化内存,并且它们返回引用类型,因此不必返回指针

让我们看一些make的例子:

 
 
 
  1. mm :=make(map[string]string)
  2.   mm["name"] = "lc"
  3.   fmt.Println(mm["name"])
  4.   mss :=make([]int,2)
  5.   mss[0] = 100
  6.   fmt.Println(mss[0])
  7.   ch :=make(chan int,1)
  8.   ch <-100
  9.   fmt.Println(<-ch)

总结:

make仅用于分配和初始化slice,map和chan类型的数据。new可以分配任何类型的数据。new分配返回一个指针,即Type * Type。make返回一个引用,该引用为Type由make分配的空间之后,清除并初始化由new分配的空间。

网站题目:Golang面试make和new的用法
文章源于:http://www.hantingmc.com/qtweb/news32/523732.html

网站建设、网络推广公司-创新互联,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联