구조체와 인터페이스
Go Interfaces
Describe behavior as a list of methods. Any type that has them satisfies the interface automatically.
배울 내용
- Defining an interface
- Implicit implementation
- any and type assertions
interface Shape
ShapeArea(), Name()CircleRect
Behavior, not inheritance
An interface lists methods. Any type that has those methods satisfies the interface automatically: there is no implements keyword. Code written against the interface works with every such type.
Circle and Rect both have Area and Name, so both can be stored in a []Shape and passed to describe. any is the interface with no methods, which every value satisfies. value.(Circle) is a type assertion: ok is true when the value really is a Circle.
핵심 포인트
- There is no implements keyword.
- A []Shape can hold different types.
value.(Circle)checks the real type.
실행 가능한 Go 예제
Go
main.go
package main
import (
"fmt"
"math"
)
type Shape interface {
Area() float64
Name() string
}
type Circle struct{ Radius float64 }
type Rect struct{ Width, Height float64 }
func (c Circle) Area() float64 { return math.Pi * c.Radius * c.Radius }
func (c Circle) Name() string { return "circle" }
func (r Rect) Area() float64 { return r.Width * r.Height }
func (r Rect) Name() string { return "rectangle" }
func describe(shape Shape) {
fmt.Printf("%s: %.2f\n", shape.Name(), shape.Area())
}
func main() {
shapes := []Shape{Circle{Radius: 1}, Rect{Width: 2, Height: 3.5}}
for _, shape := range shapes {
describe(shape)
}
var value any = shapes[0]
if circle, ok := value.(Circle); ok {
fmt.Println("radius:", circle.Radius)
}
}
circle: 3.14
rectangle: 7.00
radius: 1연습
예제를 온라인 컴파일러에서 열고 값을 바꾸거나 한 줄을 추가한 다음, 실행하기 전에 출력을 예상해 보세요. 그런 다음 일부러 코드를 망가뜨리고 컴파일러 메시지를 읽어 보세요.
이 레슨을 마쳤나요?
학습 완료로 표시하면 진행 상황을 기록할 수 있습니다.
진행 상황이 이 브라우저에 저장되어 있습니다 로그인하면 모든 기기에서 이어갈 수 있습니다.
챌린지로 연습하기
이 레슨에서 배운 내용으로 실제 문제를 풀어 보세요. 모든 챌린지는 브라우저에서 실행되며 즉시 테스트와 AI 리뷰를 받을 수 있습니다.
- 알림 비용 이메일, SMS, 푸시 채널이 각자의 방식으로 비용을 계산해 메시지를 보냅니다. 쉬움
- 도형 팩토리 팩토리로 텍스트 설명에서 도형을 만들고 각 도형의 넓이를 반환합니다. 쉬움