Menu
CoddyTech

포인터 리시버의 상태

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

C# 클래스 메서드는 공유 객체를 변경합니다. Go의 *T 리시버는 값 복사본이 아니라 원래 구조체를 변경합니다. Go는 주소를 사용할 수 있는 변수에 대한 호출에서 자동으로 주소를 가져올 수 있지만, 인터페이스에 할당할 때는 여전히 실제 메서드 집합을 확인합니다.

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

C# 예제

using System;
using System.Collections.Generic;
using System.Linq;
class Buffer{public string Text="";public void Put(string s){Text+=s;}}
class Program { static void Main() {
Buffer b=new Buffer();b.Put("x");Console.WriteLine(b.Text);
} }

소스 출력:

x

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 컴파일러