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相关文章推荐
- Go语言学习三:Go基础(iota,array,slice,map,make,new)
- [Golong]学习笔记(一) 基础知识
- [学习笔记]C和C++中指针的基础知识点(二)
- Go语言基础:make,new, len, cap, append, delete方法
- Go语言学习之new与make(The way to go)
- [Golong]学习笔记(一) 基础知识
- C++基础知识学习:new与delete表达式
- Go语言基础:make,new, len, cap, append, delete方法
- Go语言学习笔记一、基础知识
- Go基础知识学习(3)闭包
- GO--基础知识学习一
- Go基础知识学习(6) 接口
- 【Go入门教程4】变量(var),常量(const),内置基础类型(Boolean、数值 byte,int,rune、字符串、错误类型),分组,iota枚举,array(数值),slice(切片),map(字典),make/new操作,零值
- [学习笔记]C和C++中指针的基础知识点(一)
- Go基础知识学习(2) 回调函数
- Go语言基础:array、slice、make和new操作、map
- c语言学习之基础知识点介绍(十五):函数的指针
- Go学习——new()和 make()的区别详解(转载)
- [Golong]学习笔记(一) 基础知识
- Go语言基础:make,new, len, cap, append, delete方法