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의 μ‚¬μš©μ€ λ‹€μŒκ³Ό κ°™λ‹€.

결과값은 μ£Όμ†Œκ°€ λ‚˜μ˜¨λ‹€. newλŠ” μ£Όμ†Œκ°’μ„ λ¦¬ν„΄ν•œλ‹€λŠ” 것을 μ•Œ 수 μžˆλ‹€.

makeλŠ” μ–΄λ–¨κΉŒ?

makeλŠ” κ°’ 자체λ₯Ό λ°˜ν™˜ν•œλ‹€.

즉, make와 new의 μ£Όμš” 차이점은 포인터이냐 μ•„λ‹ˆλƒμ΄λ‹€.

newλŠ” 0으둜 μ΄ˆκΈ°ν™”λœ 값을 μƒμ„±ν•˜κ³  ν•΄λ‹Ή κ°’μ˜ μ£Όμ†Œλ₯Ό λ°˜ν™˜ν•˜λŠ” 반면, makeλŠ” μ΄ˆκΈ°ν™”λœ 값을 μƒμ„±ν•˜κ³  ν•΄λ‹Ή 값을 직접 λ°˜ν™˜ν•œλ‹€.

λ˜ν•œ, makeλŠ” 슬라이슀, λ§΅, 채널 같은 λ‚΄μž₯ νƒ€μž…μ—λ§Œ μ‚¬μš©λ  수 μžˆλ‹€.

기본적으둜 λ§Žμ΄λ“€ μ‚¬μš©ν•˜λŠ” 두 빌트인 ν•¨μˆ˜μ˜ 차이점에 λŒ€ν•΄μ„œ 잘 μ•Œκ³  있으면 쒋을 것이닀.

Last updated