Interfaces and Error Handling in Go Programming

Introduction

The interface is a concept used in Golang and it helps us get polymorphisms. So we don’t get the inheritance, we don’t need inheritance, we don’t need overriding. We can use interfaces to do the same thing.

The interface is a set of method signatures. So by signatures, It means the name of the method, the parameters of the method, and their types, and their return values, and their types. So that’s all it is, there are no implementations, implementation of a method. it defines the signatures to the method. It means the methods that have to have this name, these parameters, these return values.

Defining an Interface Type

here, we define an interface type. It looks sort of like a struct. we are using the type IShape interface. the keyword interface use after the name of the interface.

type IShape interface
 {
   Area() float64
   Perimeter() float64
 }
 
 type ITriangle{...}
 
 func(t Triangle) Area() float64 {..}
 func(t Triangle) Perimeter() float64 {..}

In curly brackets, we start listing the signatures of the methods. So, in this case, is only two method and two signatures that we need, area and perimeter. Both of them area and perimeter take no arguments and they return a 64 float. we list all these method signatures that we want to put in the interface.

Error Handling

The Error Interfaces has a lot of different Go functions. that are built into packages, which return errors. And when we say return errors, what they do is they return whatever they’re supposed to return.

type error interface
 {
   Error() string
 }

The error interface is any type that satisfies this interface. so, the error interfaces specifies that you have to have a method call error. which prints the error message or some other text that is useful.

So under correct operation, the error return might be nil, so for instance, let’s we have an example,

f, err := os.Open("/doc.txt")
 
 if err != nil
 {
  fmt.Println(err)
  return
 }

we want to open a file. If it opens the file perfectly, then it’ll return nil for the error, and there’s no problem. But if the error actually has a value, then you’ll print the error, and it’ll call its error method, which will successfully print the error.

the printing an error is within the format fmt package. the println is a part of that package that will call the error method of the error to generate the string, and print that string. And so, this the generic way of handling errors in Golang. It’s a very common way to handle errors in Golang.

Leave a Reply

Your email address will not be published. Required fields are marked *