Menu
CoddyTech

암묵적 인터페이스 계약

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

C++의 컴포지션은 구체적인 값을 소유하거나 다형성 의존성을 참조할 수 있습니다. Go 인터페이스를 사용하면 소비자가 암시적 구현을 통해 동작 계약을 저장할 수 있습니다. 제공된 협력 객체를 관찰 가능하게 유지하세요. 소비자 내부에서 선호하는 구체 타입을 생성하면 대체 가능성이 사라집니다.

타입은 필요한 메서드 집합을 갖추면 인터페이스를 구현합니다. implements 선언은 작성하지 않습니다. 작은 인터페이스를 받으면 호출자가 자신만의 동작을 제공할 수 있습니다. 인터페이스 값에는 동적 구체 타입과 값이 담깁니다. 동작에 변경 가능한 정체성이 필요한 경우 포인터 리시버를 일관되게 사용하세요.

C++ 예제

#include <algorithm>
#include <iomanip>
#include <iostream>
#include <map>
#include <numeric>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>
int main() {
    struct Rate { int cents; int cost(int n) const { return cents * n; } };
    struct Bill { Rate rate; int total(int n) const { return rate.cost(n); } };
    Rate rate{4};
    Bill bill{rate};
    rate.cents = 7;
    std::cout << bill.total(2) << '\n';
}

원본 출력:

8

Go 예제

package main
import ("fmt")
type Speaker interface { Speak()string }; type Bell struct{}; func(Bell)Speak()string{return "ding"}
func main(){var s Speaker = Bell{}
fmt.Println(s.Speak())}

Go 출력:

ding
challenge icon

챌린지

쉬움

Transform(int) int를 포함하는 Transformer를 정의하고, 두 배로 곱하는 기능을 구현하는 Double과 해당 메서드를 호출하는 Apply(t Transformer,n int) int를 작성하세요. 드라이버는 디스패치를 확인하기 위해 다른 구현을 제공합니다.

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

코드는 transformer.go, double.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)}}
type probeTransform struct{};func(probeTransform)Transform(n int)int{return n+7}
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)
must(Apply(probeTransform{},4)==11 && (Double{}).Transform(3)==6,"interface dispatch API");
result:=Solve(a0)
must(fmt.Sprint(a0)==before0,"input mutation")
fmt.Println(result)
}
quiz icon실력 점검

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

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

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