구조체와 인터페이스
Go Pointers: & and *
Share a value instead of copying it, so a function can change the original.
배울 내용
- & takes an address
- * follows a pointer
- nil pointers
Passing 21 to a function
double(number)
- gets a copy
- number stays 21
doubleInPlace(&number)
- gets the address
- number becomes 42
An address instead of a copy
Go copies values when it passes them to a function. A pointer holds the address of a value, so a function that receives a pointer can change the original.
double changes only its own copy, so number stays 21. &number gives the address, and *value reads or changes what is stored there. Go follows a pointer to a struct for you, so counter.Count works. A pointer that points to nothing is nil.
핵심 포인트
- Go copies arguments by default.
- &number is the address of number.
- *pointer reads or changes the value there.
실행 가능한 Go 예제
Go
main.go
package main
import "fmt"
func double(value int) {
value *= 2 // changes only the copy
}
func doubleInPlace(value *int) {
*value *= 2 // changes the original through the pointer
}
type Counter struct{ Count int }
func main() {
number := 21
double(number)
fmt.Println(number)
doubleInPlace(&number)
fmt.Println(number)
pointer := &number
*pointer = 7
fmt.Println(number, *pointer, pointer == &number)
counter := &Counter{}
counter.Count++ // Go follows the pointer for you
fmt.Println(counter.Count)
var missing *Counter
fmt.Println(missing == nil)
}
21
42
7 7 true
1
true연습
예제를 온라인 컴파일러에서 열고 값을 바꾸거나 한 줄을 추가한 다음, 실행하기 전에 출력을 예상해 보세요. 그런 다음 일부러 코드를 망가뜨리고 컴파일러 메시지를 읽어 보세요.
이 레슨을 마쳤나요?
학습 완료로 표시하면 진행 상황을 기록할 수 있습니다.
진행 상황이 이 브라우저에 저장되어 있습니다 로그인하면 모든 기기에서 이어갈 수 있습니다.
챌린지로 연습하기
이 레슨에서 배운 내용으로 실제 문제를 풀어 보세요. 모든 챌린지는 브라우저에서 실행되며 즉시 테스트와 AI 리뷰를 받을 수 있습니다.
- Swap First and Last Exchange the first and last items of a list. 쉬움
- 연결 리스트 연산 연결 리스트를 흉내 냅니다. 양 끝에 추가하고, 앞에서 또는 값으로 삭제하고, 뒤집습니다. 쉬움