File tree 3 files changed +50
-0
lines changed
3 files changed +50
-0
lines changed Original file line number Diff line number Diff line change
1
+ > new 的作用是初始化一个指向类型的指针(* T),make 的作用是为 slice,map 或 chan 初始化并返回引用(T)
Original file line number Diff line number Diff line change
1
+ package main
2
+
3
+ import "fmt"
4
+
5
+ /**
6
+ * func make(Type, size IntegerType) Type
7
+ * Only support slice, map, chan type
8
+ */
9
+
10
+ func main () {
11
+ a := make ([]int , 5 )
12
+ printSlice ("a" , a )
13
+ b := make ([]int , 0 , 5 )
14
+ printSlice ("b" , b )
15
+ c := b [:2 ]
16
+ printSlice ("c" , c )
17
+ d := c [2 :5 ]
18
+ printSlice ("d" , d )
19
+ }
20
+
21
+ func printSlice (s string , x []int ) {
22
+ fmt .Printf ("%s len=%d cap=%d %v\n " ,
23
+ s , len (x ), cap (x ), x )
24
+ }
Original file line number Diff line number Diff line change
1
+ package main
2
+
3
+ import (
4
+ "fmt"
5
+ )
6
+
7
+ // func new(Type) *Type
8
+
9
+ // 和 build-in 方法:new(int) 一样
10
+ func newInt () * int {
11
+ var i int
12
+ return & i
13
+ }
14
+ func newString () * string {
15
+ var i string
16
+ return & i
17
+ }
18
+
19
+ func main () {
20
+ myNewInt := newInt ()
21
+ fmt .Println (* myNewInt )
22
+
23
+ myNewString := newString ()
24
+ fmt .Println (* myNewString )
25
+ }
You can’t perform that action at this time.
0 commit comments