Golang new/make

Golang New/Make

golang에서 새로운 변수를 할당할 때 주로 new/make 두 가지를 사용한다.

빌트인 패키지에서도 두 함수는 사이좋게 붙어있다.

어떤 차이점이 있을까?

package builtin

// The make built-in function allocates and initializes an object of type
// slice, map, or chan (only). Like new, the first argument is a type, not a
// value. Unlike new, make's return type is the same as the type of its
// argument, not a pointer to it. The specification of the result depends on
// the type:
//
//	Slice: The size specifies the length. The capacity of the slice is
//	equal to its length. A second integer argument may be provided to
//	specify a different capacity; it must be no smaller than the
//	length. For example, make([]int, 0, 10) allocates an underlying array
//	of size 10 and returns a slice of length 0 and capacity 10 that is
//	backed by this underlying array.
//	Map: An empty map is allocated with enough space to hold the
//	specified number of elements. The size may be omitted, in which case
//	a small starting size is allocated.
//	Channel: The channel's buffer is initialized with the specified
//	buffer capacity. If zero, or the size is omitted, the channel is
//	unbuffered.
func make(t Type, size ...IntegerType) Type

// The new built-in function allocates memory. The first argument is a type,
// not a value, and the value returned is a pointer to a newly
// allocated zero value of that type.
func new(Type) *Type

사실 들어오는 타입과, 리턴 타입만 봐도 차이를 알 수 있다.

일단 한 번 예시를 보자. new의 사용은 다음과 같다.

package main

import "log"

func main() {
	var a = new(int)

	log.Println(a) // 0x...
}

결과값은 주소가 나온다. new는 주소값을 리턴한다는 것을 알 수 있다.

make는 어떨까?

package main

import "log"

func main() {
	var a = make([]int, 10)

	log.Println(a) // [0, 0, ...]
}

make는 값 자체를 반환한다.

즉, make와 new의 주요 차이점은 포인터이냐 아니냐이다.

new는 0으로 초기화된 값을 생성하고 해당 값의 주소를 반환하는 반면, make는 초기화된 값을 생성하고 해당 값을 직접 반환한다.

또한, make는 슬라이스, 맵, 채널 같은 내장 타입에만 사용될 수 있다.

기본적으로 많이들 사용하는 두 빌트인 함수의 차이점에 대해서 잘 알고 있으면 좋을 것이다.

Last updated