Go 인터페이스

1 개요[ | ]

Go 인터페이스


2 예시: Animal[ | ]

package main

import "fmt"

type Animal interface {
	AnimalSound()
	Sleep()
}

type Dog struct{}

func (d *Dog) AnimalSound() {
	fmt.Println("bark")
}

func (d *Dog) Sleep() {
	fmt.Println("zzz")
}

func main() {
	var a Animal = &Dog{}
	a.AnimalSound()
	a.Sleep()
}
package main

import "fmt"

type Animal interface {
	AnimalSound()
	Sleep()
}

type Dog struct{}

func (d Dog) AnimalSound() {
	fmt.Println("bark")
}

func (d Dog) Sleep() {
	fmt.Println("zzz")
}

func main() {
	var a Animal = Dog{}
	a.AnimalSound()
	a.Sleep()
}

3 예시: Shape[ | ]

package main

import (
	"fmt"
	"math"
)

type Shape interface {
	Area() float64
}

type Rect struct {
	width, height float64
}

func (r *Rect) Area() float64 { return r.width * r.height }

type Circle struct {
	radius float64
}

func (c *Circle) Area() float64 {
	return math.Pi * c.radius * c.radius
}

func main() {
	rect := &Rect{5, 40}
	circle := &Circle{10}

	fmt.Println("rect area:", rect.Area())     // rect area: 200
	fmt.Println("circle area:", circle.Area()) // circle area: 314.1592653589793
}
package main

import (
	"fmt"
	"math"
)

type Shape interface {
	Area() float64
}

type Rect struct {
	width, height float64
}

func (r Rect) Area() float64 { return r.width * r.height }

type Circle struct {
	radius float64
}

func (c Circle) Area() float64 {
	return math.Pi * c.radius * c.radius
}

func main() {
	rect := Rect{5, 40}
	circle := Circle{10}

	fmt.Println("rect area:", rect.Area())     // rect area: 200
	fmt.Println("circle area:", circle.Area()) // circle area: 314.1592653589793
}

4 예시[ | ]

// https://tour.golang.org/methods/9
package main

import (
	"fmt"
	"math"
)

type Abser interface {
	Abs() float64
}

func main() {
	var a Abser
	f := MyFloat(-math.Sqrt2)
	v := Vertex{3, 4}

	a = f  // a MyFloat implements Abser
	a = &v // a *Vertex implements Abser

	// In the following line, v is a Vertex (not *Vertex)
	// and does NOT implement Abser.
	// a = v

	fmt.Println(a.Abs())
}

type MyFloat float64

func (f MyFloat) Abs() float64 {
	if f < 0 {
		return float64(-f)
	}
	return float64(f)
}

type Vertex struct {
	X, Y float64
}

func (v *Vertex) Abs() float64 {
	return math.Sqrt(v.X*v.X + v.Y*v.Y)
}

5 같이 보기[ | ]

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}