go语言的new和make

leonpengweicn · · 1199 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

http://1.guotie.sinaapp.com/?p=407

golang的new和make主要区别如下:

1、make只能用来分配及初始化类型为slice,map,chan的数据;new可以分配任意类型的数据

2、new分配返回的是指针,即类型*T;make返回引用,即T;

3、new分配的空间被清零,make分配后,会进行初始化。effective go举了一个例子,见:http://golang.org/doc/effective_go.html#allocation_make

对于struct的分配和初始化,除了可以使用new外,还可以这样做: T {},例如

func TestAlloc(t *testing.T) {
	type T struct {
		n  string
		i  int
		f  float64
		fd *os.File
		b  []byte
		s  bool
	}

	var t1 *T
	t1 = new(T)
	fmt.Println(t1)

	t2 := T{}
	fmt.Println(t2)

	t3 := T{"hello", 1, 3.1415926, nil, make([]byte, 2), true}
	fmt.Println(t3)
}

值得注意的是,如果使用T{}的方式初始化变量的话:
1、与C语言不同,T{}分配的局部变量是可以返回的,且返回后该空间不会释放,例如

import "fmt"
type T struct {
    i, j int
}
func a(i, j int) T {
    i := T { i, j}
    return i
}
func b {
    t = a(1, 2)
    fmt.Println(t)
}

2、一个语法问题
使用T{}来初始化时,符号}不能单独占一行,否则会报错,如下:

missing ',' before newline in composite literal

或者

syntax error: need trailing comma before newline in composite literal
non-declaration statement outside function body
syntax error: unexpected }

我曾经因为这个问题找了很久才解决。



有疑问加站长微信联系(非本文作者)

本文来自:CSDN博客

感谢作者:leonpengweicn

查看原文:go语言的new和make

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

1199 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传