我为什么要做()或新的()? [英] Why would I make() or new()?

查看:61
本文介绍了我为什么要做()或新的()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

介绍文件用了很多段落来解释 new() make()之间的区别,但是在你可以在本地范围内创建对象并返回它们。

您可以使用 make 来做任何其他方式的事情:

b
$ b

  • 创建频道

  • 创建一个预先分配空间的地图

  • 预先分配的空间或带有空格的切片!= cap



证明 new 。它更容易的主要事情是创建指向非复合类型的指针。
下面的两个函数是等价的。一个简单一点:$ b​​
$ b $ p $ func newInt1()* int {return new(int)}

func newInt2()* int {
var i int
return& i
}


The introduction documents dedicate many paragraphs to explaining the difference between new() and make(), but in practice, you can create objects within local scope and return them.

Why would you use the (frankly silly) pair of allocators?

解决方案

Things you can do with make that you can't do any other way:

  • Create a channel
  • Create a map with space preallocated
  • Create a slice with space preallocated or with len != cap

It's a little harder to justify new. The main thing it makes easier is creating pointers to non-composite types. The two functions below are equivalent. One's just a little more concise:

func newInt1() *int { return new(int) }

func newInt2() *int {
    var i int
    return &i
}

这篇关于我为什么要做()或新的()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆