암묵적 인터페이스 계약
Coddy의 Ruby 개발자를 위한 Go 코스 레슨. 48개 중 30번째.
Ruby에서 컴포지션은 덕 타이핑에 의존하는 경우가 많습니다. 요청된 메서드를 가진 협력 객체라면 무엇이든 사용할 수 있습니다. Go에서는 인터페이스로 이러한 기대를 표현하고, 메서드 집합을 확인합니다. 구현은 implements 선언 없이 암묵적으로 이루어집니다. 실제로 전달된 객체에 계속 위임하세요.
필요한 메서드 집합을 갖추면 타입은 인터페이스를 구현합니다. implements 선언은 작성하지 않습니다. 작은 인터페이스를 받아들이면 호출자가 자신만의 동작을 제공할 수 있습니다. 인터페이스 값에는 동적 구체 타입과 값이 담깁니다. 동작에 변경 가능한 정체성이 필요하다면 포인터 리시버를 일관되게 사용하세요.
Ruby 예제
class Rate
def initialize(cents)
@cents = cents
end
def cost(units)
@cents * units
end
end
class Bill
def initialize(rate)
@rate = rate
end
def total(units)
@rate.cost(units)
end
end
puts Bill.new(Rate.new(7)).total(2)소스 출력:
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를 정의하고, 2를 곱하는 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)
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
Ruby 개발자를 위한 Go의 모든 레슨
직접 연습해 보세요: 온라인 Go 컴파일러