You have 2 free member-only stories left this month.

For those who don’t know Go’s interface

Introduction

interfaceI would like people who are studying the Go language to read it because it is difficult to understand when it gets involved.
In particular, Tour of Go of Stringers assumes that you no longer know as per se.

Also, since the purpose is to deepen the understanding compared to Java, I think it will be a piercing explanation for those who have experience with Java.

Why I don’t understand

I think there are two causes.

  • I don’t understand the concept of interface well in the first place
  • I misunderstand that an explicit implementation is a prerequisite

The former does not know that completely different types (classes) can be treated as interface types and partly the same.

The latter is confused about how to write Go because he thinks too much about Java’s explicit interface implementation.

I think that’s what it means.

Implementation example of an interface (Theme: What does eating mean?)

package mainimport "fmt"// Interface for eating
type Eater interface {
PutIn () // Put in your mouth
Chew () // chew
Swallow () // swallow
}
// Human structure
type Human struct {
Height int // Height int //
}
// Turtle structure
type Turtle struct {
Kind string // Type
}
// Implementation of human interface
func (h Human) PutIn () {
fmt.Println ("Use a tool carefully")
}
func (h Human) Chew () {
fmt.Println ("bite firmly with teeth")
}
func (h Human) Swallow () {
fmt.Println ("If you chew well, swallow")
}
// Implementation of interface for turtles
func (h Turtle) PutIn () {
fmt.Println ("If you find a prey, quickly stretch your neck and bite")
}
func (h Turtle) Chew () {
fmt.Println ("Crush with a beak")
}
func (h Turtle) Swallow () {
fmt.Println ("If you crush it into small pieces, swallow it")
}
// Eating method with interface as an argument
func EatAll (e Eater) {
e.PutIn () // Call from interface
e.Chew ()
e.Swallow ()
}
func main () {
var man Human = Human {Height: 300} // Create a structure for humans
var cheloniaMydas = Turtle {Kind: "Green Turtle"} // Create a structure for the turtle
var eat Eater // Prepare a variable of interface Eater type
fmt.Println ("<Eat by humans>")
eat = man // Human type is converted to interface Eater type
EatAll (eat) // Call a function with an interface as an argument
fmt.Println ("<Turtle eats>")
eat = cheloniaMydas // Turtle type is converted to Eater type which is an interface
EatAll (eat)
}
## Outputs

<Eat by humans>
Use a tool carefully
bite firmly with teeth
If you chew well, swallow
<Turtle eats>
If you find a prey, quickly stretch your neck and bite
Chew with a beak
If you crush it into small pieces, swallow it

The code has become quite long, but I’ll explain it properly so please follow me.
Then, I will introduce it in the following four phases.

  • Interface definition
  • Functions using interfaces
  • Interface implementation
  • How to use the interface

Interface definition

// Interface for eating
type Eater interface {
PutIn () // Put in your mouth
Chew () // chew
Swallow () // swallow
}
// Human structure
type Human struct {
Height int // Height int //
}
// Turtle structure
type Turtle struct {
Kind string // Type
}

First, let’s think about expressing “eating” in a program.
I defined the function in the interface by dividing it into phases such as putting it in the mouth, chewing it, and swallowing it.

The answer is different for each person, but this time I will try to make it like this.

Next, I defined a structure (corresponding to a class in Java).

It is a human structure and a turtle structure. The point is that “the contents of each structure can be completely different”.

Functions using interfaces

// Eating method with interface as an argument
func EatAll (e Eater) {
e.PutIn () // Call from interface
e.Chew ()
e.Swallow ()
}

The final goal of this time is easy to understand if you think of it as “creating a function that takes an interface as an argument EatAll".

As a first step, we first defined the interface.

What makes you happy when you take an interface as an argument?
For example, by doing this, it seems that you can reuse the interface you mentioned earlier when expressing “drinking” in a program. It’s a liquid so you don’t have to chew it.

// A drinking method with an interface as an argument
func DrinkAll (e Eater) {
e.PutIn () // Call from interface
e.Swallow ()
}

It looks like this when written in a program.

Interface implementation

This is where I was most confused.

In Java:

class Human implements Eater {
private int height;
public void PutIn () {
System.out.println ("Using tools ...");
}
// ...
}

It should look like this.

The decisive difference from Java is that there is noimplements. Please note here. In Go, think that it will be automatically implemented in the structure where all the functions with the same function name in the interface are implemented.

// Implementation of human interface
func (h Human) PutIn () {
fmt.Println ("Use a tool to carefully bring it to your mouth")
}
func (h Human) Chew () {
fmt.Println ("bite firmly with teeth")
}
func (h Human) Swallow () {
fmt.Println ("If you chew well, swallow")
}
// Implementation of interface for turtles
func (h Turtle) PutIn () {
fmt.Println ("If you find a prey, quickly stretch your neck and bite")
}
func (h Turtle) Chew () {
fmt.Println ("Crush with a beak")
}
func (h Turtle) Swallow () {
fmt.Println ("If you crush it into small pieces, swallow it")
}

In this part, we use the receiver and define three methods for each Humanand Turtleboth.

Try, eating.goKara Human's Swallow()what happens when they pull out.

source_file.go:56: cannot use man (type Human) as type Eater in assignment:     Human does not implement Eater (missing Swallow method)

It will be like this.
It mainmaybe confusing because we haven't explained the contents of the function yet.

This says that the Humantype Eatercannot be used to assign it as an interface type.

This means that the Humantype Eaterdoes not implement the interface type.
On the flip side, all you have to do is implement all the methods with the same name in the interface and the interface will be implemented automatically.

How to use the interface

Finally, I mainwill introduce the contents of the function.

func main () {
var man Human = Human {Height: 300} // Create a structure for humans
var cheloniaMydas = Turtle {Kind: "Green Turtle"} // Create a structure for the turtle
var eat Eater // Prepare a variable of interface Eater type
fmt.Println ("<Eat by humans>")
eat = man // Human type is converted to interface Eater type
EatAll (eat) // Call a function with an interface as an argument
fmt.Println ("<Turtle eats>")
eat = cheloniaMydas // Turtle type is converted to Eater type which is an interface
EatAll (eat)
}

The first two lines just define the structure.

The third line defines a variable of type interface Eater. This is the point. This variable eatis just a Eatertype. Again, it's an interface.

And in the 5th line, Humanthe substance of the type structure is put in the interface type variable. At this point, Eaterthink of it as being converted to a type.

And in the 6th line EatAll, eatwe pass the interface to the function explained earlier.

Do this for turtles as well.

Then you can see that the results are different for humans and turtles.

Think of this in Stringer

I brought what appears in the Tour of Go as it is.
What this tutorial says is

type Stringer interface {
String() string
}
  • fmt.StringerThe interface in the first place is defined above.
  • fmt.StringerIs fmtare using this interface as the argument of a function that is in the package.

fmtTypical functions in the package are fmt.Println. This fmt.Stringermeans that you can also use this argument.

Now let’s implement it.
How did you implement it? implementsThere is no such thing. that's right. Once you have implemented all the functions in the interface in the type you want to implement, that's it.

type Person struct {
Name string
Age int
}
func (p Person) String() string {
return fmt.Sprintf("%v (%v years)", p.Name, p.Age)
}

This time Person... we want to implement in
the receiver Persona, and, to make the function of the same name as a function that is in the Stringer, was combined argument of type, also the type of the return value!

This completes the implementation.

By signing up, you will create a Medium account if you don’t already have one. Review our Privacy Policy for more information about our privacy practices.

Medium sent you an email at to complete your subscription.

https://www.khanakia.com/

Share your ideas with millions of readers.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

How can we make get/post requests using PHP

PYTHON SQLITE3

An integrated approach to Designing and Coding

Software Support — Agency or Freelancer?

The Facilis framework for dotnet core — the primary key

Asp.Net Core 5 ile CQRS ve MediatR Kullanılması

Dockerizing Pulldasher 2: Docker Compose

Is Python past tense? Is Golang the future? Python vs Go 2020

Aman Khanakia

Aman Khanakia

https://www.khanakia.com/

More from Medium

How to Create an Authentication API with Golang

What is the syntax to comment code in Golang?

Some patterns for HTTP and Unit Testing in Go

A Go Debugging Anti-Pattern