암묵적 인터페이스 계약
Coddy의 PHP 개발자를 위한 Go 코스 레슨. 48개 중 30번째.
PHP에서는 클래스가 인터페이스를 명시적으로 구현합니다. Go에서는 메서드 집합이 일치하면 인터페이스를 암묵적으로 만족합니다. 제공된 정책이나 의존성을 저장하고, 하드 코딩된 구현을 생성하는 대신 이를 호출하세요. implements 키워드가 없다고 해서 동작 계약이 약해지는 것은 아닙니다.
타입은 필요한 메서드 집합을 갖추면 인터페이스를 구현합니다. implements 선언은 작성하지 않습니다. 작은 인터페이스를 받으면 호출자가 자체 동작을 제공할 수 있습니다. 인터페이스 값에는 동적 구체 타입과 값이 담깁니다. 동작에 변경 가능한 정체성이 필요한 경우 포인터 리시버를 일관되게 사용하세요.
PHP 예제
<?php
class Rate { public $cents = 7; public function cost($n) { return $this->cents * $n; } }
class Bill {
public $rate;
public function __construct($rate) { $this->rate = $rate; }
public function total($n) { return $this->rate->cost($n); }
}
echo (new Bill(new Rate()))->total(2), "\n";소스 출력:
14Go 예제
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챌린지
쉬움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)
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
PHP 개발자를 위한 Go의 모든 레슨
직접 연습해 보세요: 온라인 Go 컴파일러