Menu
CoddyTech

포인터 리시버의 상태

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

JavaScript 객체는 공유 참조이므로, this.text에 할당하면 해당 객체가 변경됩니다. Go에서는 일반적으로 수신자의 필드를 변경하려면 포인터 수신자가 필요합니다. 메서드 호출 시 주소를 자동으로 취한다고 해서 T와 *T가 인터페이스를 동일하게 구현하는 것은 아닙니다.

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

JavaScript 예제

class Buffer{constructor(){this.text="";}put(s){this.text+=s;}}const b=new Buffer();b.put("x");console.log(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를 확인하고 호출자의 입력을 보존합니다. 컬렉션의 stdout 출력에는 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실력 점검

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

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

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