관심있는 것들 정리

Golang 연습 5 (duck typing using interface) 본문

programming/Golang

Golang 연습 5 (duck typing using interface)

내공강화 2021. 1. 26. 09:11

실제 타입이 아닌 구현된 메소드만을 이용해 타입을 판단하는 덕타이핑

 

package main

import (
	"fmt"
)

type Duck struct {
}

func (d Duck) quack() {
	fmt.Println("Quack~")
}

func (d Duck) feather() {
	fmt.Println("Flutter")
}

type Person struct {
}

func (p Person) quack() {
	fmt.Println("Says Quack")
}

func (p Person) feather() {
	fmt.Println("Swing two arms")
}

type Action interface {
	quack()
	feather()
}

func handle(a Action) {
	a.quack()
	a.feather()
}

func main() {
	var little Duck
	var johnDoe Person

	handle(little)
	handle(johnDoe)
}
반응형