Skip to content

Commit 2ac49e0

Browse files
committed
✨ new & make
1 parent 634f4ca commit 2ac49e0

File tree

3 files changed

+50
-0
lines changed

3 files changed

+50
-0
lines changed

type/README.md

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
> new 的作用是初始化一个指向类型的指针(*T),make 的作用是为 slice,map 或 chan 初始化并返回引用(T)

type/make/main.go

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
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+
}

type/new/main.go

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
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+
}

0 commit comments

Comments
 (0)