Interface/Method/Error Handling
✅ Interface
- Interface:
- 1️⃣ Go’s equivalent of Java’s
Object class
- most general type
any value can be stored in a variable of type
interface{}
- 2️⃣ set of methods to be implemented on several objects
- inside interface
shape
, mention function namearea()
- if an object
circle
has that functionarea()
➡️
circle
implements theshape
interface- can implement more than one interface
- object should have ALL the functions in interface
1️⃣ interface as most general type
1
2
3
4
5
6
7
8
//create interface
box := interface{}("hello") //can assign any type to interface
func describeValue(t interface{}) {
fmt.Printf("%T, %v\n", t, t)
}
describeValue(box) //string, hello
2️⃣ interface as set of methods
- ☑️ example 1:
Circle
andRect structs
implementShape interface
1
2
3
4
Shape Interface
[area()]
/ \
Circle Rect
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
// create interface
type Shape interface {
//any object that has area() is implementing type Shape
area() float64 //return float64
}
type Circle struct {
radius float64
}
type Rect struct {
width float64
height float64
}
//circle has area() -> implements shape interface
func (c Circle) area() float64 {
return c.radius * c.radius * 3.14
}
//rect has area() -> implements shape interface
func (r Rect) area() float64 {
return r.height * r.width
}
//can make function with shape interface
func getArea(s Shape) float64 {
return s.area()
}
1
2
3
4
5
6
7
8
9
10
11
12
func main() {
c1 := Circle{4.5}
r1 := Rect{5, 20}
//implement interface, can put both circle and rect in Shape
shapes := []Shape{c1, r1}
for _, shape := range shapes {
fmt.Println(shape.area()) //use interface function
fmt.Println(getArea(shape)) //use function that reference interface
}
}
- ☑️ example 2:
Shape
andMesurable interface
implementGeometry interface
struct Rect
implementsShape
andMesurable interface
1
2
3
4
5
6
Geometry Interface
/ \
Shape Interface Mesurable Interface
[area()] [permimeter()]
\ /
Rect
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
type Geometry interface {
Shape
Measurable
}
type Shape interface {
area() float64
}
type Measurable interface {
perimeter() float64
}
type Rect struct {
width, height float64
}
func (r Rect) area() float64 {
return r.width * r.height
}
func (r Rect) perimeter() float64 {
return (r.width + r.height) * 2
}
func describeShape(g Geometry) { //geometry as param
fmt.Println("Area: ", g.area())
fmt.Println("Perimeter: ", g.perimeter())
}
func main() {
rect := Rect{4, 5}
describeShape(rect)
}
Function 🆚 Method
- function: NOT tied to any type
- method: function with reciever
- method is called by invoking them on an instance of a particular type
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
type Rectangle struct {
width float64
height float64
}
//get area function
func Area(r Rectangle) float64 {
return r.height * r.width
}
//call function
rectangle := Rectangle{10, 5}
Area(rectangle)
//🆚 get area method
func (r Rectangle) Area() float64 {
return r.height * r.width
}
//call method
rectangle := Rectangle{10, 5}
rectangle.Area() //reciever is rectangle
✅ Method
- tied to a specific type(
struct
), often used with stucts and interfaces
1
2
3
4
5
//define method
func (receiverName ReceiverType) MethodName(args)
//call method
instance.MethodName()
✅ Error handling with Error Interface
- ☑️ Go built-in
Error Interface
looks like this - to implement
Error Interface
, need to createError()
function
1
2
3
type error interface {
Error() string
}
- ☑️ error message interface
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
type CalculationError struct {
message string
}
func (ce CalculationError) Error() string { //implement error interface
return ce.message
}
func calculate(val float64) (float64, error) { //calculate method, can return error message
if val < 0 {
return 0, CalculationError{"Invalid input"}
}
return math.Sqrt(val), nil
}
func main(){
result, err := calculate(-9)
if err != nil {
fmt.Println(err)
} else {
fmt.Println(result)
}
}
✅
✅
✅
✅
✅
✅
✅
✅
This post is licensed under CC BY 4.0 by the author.