Programming/golang2022. 9. 6. 15:27

new는 c의 malloc()에 대응한다면

make는 특정 경우에 대한 메모리 할당 + 초기화를 위한 키워드인 듯.

package main

import "fmt"

func sum(s []int, c chan int) {
sum := 0
for _, v := range s {
sum += v
}
c <- sum // send sum to c
}

func main() {
s := []int{7, 2, 8, -9, 4, 0}

c := make(chan int)
go sum(s[:len(s)/2], c)
go sum(s[len(s)/2:], c)
x, y := <-c, <-c // receive from c

fmt.Println(x, y, x+y)
}

[링크 : https://go.dev/tour/concurrency/2]

 

Allocation with new
Go has two allocation primitives, the built-in functions new and make. They do different things and apply to different types, which can be confusing, but the rules are simple. Let's talk about new first. It's a built-in function that allocates memory, but unlike its namesakes in some other languages it does not initialize the memory, it only zeros it. That is, new(T) allocates zeroed storage for a new item of type T and returns its address, a value of type *T. In Go terminology, it returns a pointer to a newly allocated zero value of type T.
Since the memory returned by new is zeroed, it's helpful to arrange when designing your data structures that the zero value of each type can be used without further initialization. This means a user of the data structure can create one with new and get right to work. For example, the documentation for bytes.Buffer states that "the zero value for Buffer is an empty buffer ready to use." Similarly, sync.Mutex does not have an explicit constructor or Init method. Instead, the zero value for a sync.Mutex is defined to be an unlocked mutex.

[링크 : https://go.dev/doc/effective_go#allocation_new]

 

Allocation with make
Back to allocation. The built-in function make(T, args) serves a purpose different from new(T). It creates slices, maps, and channels only, and it returns an initialized (not zeroed) value of type T (not *T). 

[링크 : https://go.dev/doc/effective_go#allocation_make]

[링크 : https://pronist.dev/102]

 

'Programming > golang' 카테고리의 다른 글

golang range  (0) 2022.09.06
golang mutex  (0) 2022.09.06
golang defer 와 panic(), recover()  (0) 2022.09.06
go 루틴  (0) 2022.09.06
golang https server  (0) 2022.09.05
Posted by 구차니

댓글을 달아 주세요