您的位置:首页 > 编程语言 > Go语言

Go基础知识学习(5) 指针,new, make

2014-08-08 17:45 896 查看

指针,new , make的使用场景

Golang的指针是没有++和–操作的,*运算和&运算和C一致
Golang的new创建是返回的是指针,var返回的0值变量
Golang结构体的初始化,结构体变量的复合初始化,结构体指针的成员初始化
Golang make仅仅可以创建slice map channel 而且返回的不是指针

内存分配:
Go有两个内存分配原语 new 和 make,他们应用于不同的类型。内建函数new本质上和其他语言的new一样,
new(T)分配了零值填充的T类型的内存空间,返回一个指针,即T类型的值。
而make不同,它使用make内建函数而且目前仅能创建slice、map、channel,它返回的是类型T,不是T.

代码

package main

import (
"fmt"
)

type City struct {
name string
code int
}

func main() {
// pointer
i := 10
p := &i
fmt.Println(i)
fmt.Println(p)
fmt.Println(*p)
*p = 20
fmt.Println(i)
fmt.Println(p)
fmt.Println(*p)

//new var is diff
var c1 City
c2 := new(City)
fmt.Println(c1) //it is city
fmt.Println(c2) //it is address of city

//init
c3 := City{name: "hangzhou", code: 310000}
c4 := new(City)
c4.name = "shanghai"
c4.code = 330000
fmt.Println(c3) //it is city
fmt.Println(c4) //it is pointer of city

//make only create slice 、map 、channel
//there are not pointer
s := make([]int, 10, 20)
fmt.Println(s, len(s), cap(s))
m := make(map[int]string)
m[10] = "Google"
m[19] = "Microsoft"
fmt.Println(m)
}


output

10
0xc084000038
10
20
0xc084000038
20
{ 0}
&{ 0}
{hangzhou 310000}
&{shanghai 330000}
[0 0 0 0 0 0 0 0 0 0] 10 20
map[10:Google 19:Microsoft]


获取代码:

https://github.com/panyingyun/gostudy/blob/master/exp7.go
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: