백엔드/Go := Golang

[ Golang ] 배열 값 이해

잡캐헨리 2024. 6. 14. 22:34

Go는 기본적으로 참조가 아닌 값으로 동작하고, 배열에서도 마찬가지이다. 즉, 새 변수에 배열을 할당하면 배열을 복사하고 배열에 포함한 값을 복사한다.

Go works with values rather than references by default, and this is also true for arrays. That is, when you assign an array to a new variable, it copies the array and the values it contains.

 

배열의 참조를 생성하기 위해서는 포인터를 사용할 수 있다.

To create a reference to an array, you can use pointers.

package main

import "fmt"

func main() {
	array := [2]string{"test", "needToBeChange"}
	pointedArr := &array

	fmt.Println("Arr:", array)
	fmt.Println("pointedArr:", *pointedArr)
	array[1] = "isChanged"

	fmt.Println("Arr:", array)
	fmt.Println("pointedArr:", *pointedArr)
}

// Arr: [test needToBeChange]
// pointedArr: [test needToBeChange]
// Arr: [test isChanged]
// pointedArr: [test isChanged]