Menu
CoddyTech

포인터 리시버의 상태

Coddy의 C++ 개발자를 위한 Go 코스 레슨. 48개 중 27번째.

C++ 멤버 메서드는 암묵적으로 this를 받으며, const 메서드는 이를 통한 변경을 제한합니다. Go에서는 값 또는 포인터 리시버를 명시적으로 선언합니다. 값 리시버는 구조체를 복사하고, 포인터 리시버는 구조체를 갱신할 수 있습니다. Go에는 const 리시버 한정자가 없으며, 리시버의 메서드 집합은 인터페이스 충족 여부에 영향을 줍니다.

포인터 리시버는 원래 값을 변경할 수 있습니다. 주소를 지정할 수 있는 변수의 경우, 포인터 메서드를 호출할 때 Go가 자동으로 해당 변수의 주소를 가져올 수 있습니다. 이러한 편의 기능이 인터페이스에 할당될 때 값과 포인터의 메서드 집합이 같다는 뜻은 아닙니다.

C++ 예제

#include <algorithm>
#include <iomanip>
#include <iostream>
#include <map>
#include <numeric>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>
int main() {
    struct Counter {
        int value = 0;
        int add(int amount) { value += amount; return value; }
    };
    Counter counter;
    auto callback = [&counter](int x) { return counter.add(x); };
    int result = callback(3);
    std::cout << result << ' ' << counter.value << '\n';
}

출력 결과:

3 3

Go 예제

package main
import ("fmt")
type Buffer struct { text string }; func(b *Buffer) Put(s string) { b.text+=s }
func main(){b:=Buffer{}
b.Put("x")
fmt.Println(b.text)}

Go 출력:

x
challenge icon

챌린지

쉬움

내부 값 int, Add(delta int), Value() int를 사용해 Counter를 구현하세요. Add는 이 카운터를 변경합니다. Solve는 start 값으로 카운터를 만든 다음 delta를 더합니다.

선언된 API를 구현하고, 출력하지 말고 결과를 반환하세요. 드라이버는 필수 API를 확인하고 호출자의 입력을 보존합니다. 컬렉션의 표준 출력은 JSON이 아닌 Go 대괄호 형식을 사용합니다.

코드는 counter.go, exercise.go에 작성하세요. main.go에는 제공된 입력/출력 코드가 있으며 수정할 수 없습니다. 하나의 평면적인 package main을 유지하고 두 번째 main을 추가하지 마세요.

직접 해보기

package main
import ("fmt";"strings";"strconv";"bufio";"os")
var input []string
func L(i int)string{if i<len(input){return input[i]};return ""}
func I(i int)int{n,e:=strconv.Atoi(L(i));if e!=nil{panic(e)};return n}
func Ints(i int)[]int{out:=[]int{};if L(i)==""{return out};for _,s:=range strings.Split(L(i),","){n,e:=strconv.Atoi(s);if e!=nil{panic(e)};out=append(out,n)};return out}
func Words(i int)[]string{if L(i)==""{return []string{}};return strings.Split(L(i),",")}
func must(ok bool,message string){if !ok{panic("API: "+message)}}

func main(){
scanner:=bufio.NewScanner(os.Stdin);for scanner.Scan(){input=append(input,scanner.Text())};if scanner.Err()!=nil{panic(scanner.Err())}
a0:=I(0); before0:=fmt.Sprint(a0)
a1:=I(1); before1:=fmt.Sprint(a1)
c:=Counter{}; d:=Counter{}; c.Add(3); c.Add(-1); must(c.Value()==2 && d.Value()==0,"Counter state API");
result:=Solve(a0,a1)
must(fmt.Sprint(a0)==before0,"input mutation")
must(fmt.Sprint(a1)==before1,"input mutation")
fmt.Println(result)
}
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

C++ 개발자를 위한 Go의 모든 레슨

직접 연습해 보세요: 온라인 Go 컴파일러