Go lang - 10 : 포인터 1

개발조아·2022년 3월 26일
0

go-lang

목록 보기
10/13

값에 의한 호출

Go는 값에 의한 호출을 사용하는 언어라고 한다
함수에 파라미터로 넘겨지는 변수가 있으면 "반드시" 복사본을 만들어 넘긴다

그렇다면 외부 함수에서 값을 변경해본다면 변경이 적용될까?

Test1 & Test2

package main

import "fmt"

func modify(a map[int]string) {
	a[0] = "modified"
}

func modifyFail(a int) {
	a = 3
}

func main() {
	test1 := 99

	test2 := map[int]string{
		0: "test",
	}

	modifyFail(test1)		// 변경 X
	modify(test2)			// 변경 O

	fmt.Println(test1)
	fmt.Println(test2)
}

Console

분명 modifyFail 은 값을 단순히 "복사" 했기 때문에
test1 은 변경되지 않는다

그러나 test2 는 변수를 변경했다.

그 이유는 Go 가 Pointer 를 사용하고 map 은 Pointer 를 통해 작동하기 때문이다.

Go 의 포인터를 배워보자

profile
https://github.com/askePhoenix

0개의 댓글