Post

Go interfaces

How to define and implement interfaces in Go, demonstrated with a Shape interface that requires Area and Perimeter methods.

This program demonstrates Go interfaces. A Shape interface is defined with Area() and Perimeter() methods. The Rect struct implements both methods, which means it implicitly satisfies the Shape interface without any explicit declaration. The example shows how a Rect value can be assigned to a Shape variable and how methods can be called through both the interface and the concrete type.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
// package main

// import (
// 	"fmt"
// 	// "strconv"
// 	// "math"
// 	// "reflect"
// 	// "net/http"
// 	// "log"

// )

// // define interface
// type Writer interface {
// 	Write([]byte) (int, error)
// }

// type ConsoleWriter struct {}

// func (cw ConsoleWriter) Write(data []byte) (int, error) {
// 	n, err := fmt.Printf("Converts bytes to string: %v\n", string(data))
// 	return n, err
// }

// func main()  {
// 	var w Writer = ConsoleWriter{}
// 	w.Write([]byte("101010100001"))
// }

package main

import (
	"fmt"
)

type Shape interface {
	Area() float64
	Perimeter() float64

}

type Rect struct {
	width float64
	hight float64
}

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

func (r Rect) Perimeter() float64 {
	return 2 * (r.width + r.hight)
}

func main()  {
	var s Shape = Rect{
		width: 5.0,
		hight: 4.0,
	}

	r := Rect{
		width: 5.0,
		hight: 4.0,
	}

	fmt.Printf("%v\n", s.Perimeter())
	fmt.Printf("%v\n", s.Area())
	fmt.Printf("%T\n", s)

	fmt.Printf("%v\n", r.Perimeter())
	fmt.Printf("%v\n", r.Area())
	fmt.Printf("%T\n", r)
}

This post is licensed under CC BY 4.0 by the author.