Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Last Updated: Mar 27, 2024

Go Interface Type

Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

Whenever we talk about web development or web programming, we always talk about the two most used languages C++ and Java. But are they the only options available? Is there any other programming language that can fill those gaps of C++ and Java and can make the process of software development simplified, even for complex architecture? This question is yes, and  Golang is that same programming language. In this article, you will get to know more about Golang and its interface types. Firstly, let's then get a little idea of what the Go language is precise.

What Is Go Language?

Go is an open-source language that has resulted from collaborative work by a team at Google and various other contributors. This language assures code efficiency that helps translate faster software and applications for all businesses. Ventures like Google, Apple, Facebook, BBC, The New York Times, and various others have adopted Golang as their choice for web development language. 

Golang has been developed based on the language C. Therefore, it inherits the disciplined syntax of  C, with a few modifications and improvements here and there, which will allow developers to manage the memory safely. Go language helps in getting rid of the memory leakage issues which are encountered when developers do not release the unused memory.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

What are Interfaces and Go Interface Type?

In Go language interfaces are quite different from other languages. Interfaces in general are a set of function signatures of some specific types. In languages like Java and C++, we need to implement interfaces explicitly. Here in the case of Golang, on the other hand, the interfaces are of custom type and require no explicit declaration of intent.

The task of an interface is to provide function signatures that consist of names, input arguments, and the return types and the implementation of the interface depends on the type. An interface type in Golang is a definition that defines and describes the exact methods that some other type should be having. In Golang interface is abstract, that is we cannot create an instance of the interface but we can create a variable of an interface type. This particular variable can be assigned with a concrete type value consisting of those particular methods required by the interface. So just to be putting it in the most simple words, an interface is a collection of different methods and also a custom type.

How to create a Go Interface?

Now that we have understood, what an interface type is, let's find out how can we actually create an interface in the Go language. Following is the syntax to create an interface.

Syntax 

type  <interface_name> interface
{
	//Method Signatures
}

Example 

type  firstinterface interface  // Creating an interface
{
	func1() int  //Methods
}

In the above example, the interface name is- 'firstinterface'. 'type' and 'interface' are the keywords and all the method signatures are enclosed within the curly braces. So here we can say that something will satisfy the interface named 'firstinterface' or basically would implement the interface if it has a method with the same signature as ' func1() int’

How are interfaces implemented?

In the case of Golang, it becomes necessary for the developer to declare all the methods in the interface, in order to implement that particular interface. Interfaces are implemented implicitly in Go language and hence it doesn’t require any specific keyword to implement it, unlike other languages.

For Example 

type mock interface
{
	Peven() int
	Podd() int
}
type value struct 
{
	Even int
	Odd int
}
func (A value) Peven() int
{
	return  2*(A.Even)
}
func (A value) Podd() int
{
	return (2*(A.Odd))+1
}

Explanation 

In the above example, the 'value' type satisfies the interface because it has an int method and it doesn't matter what this 'value' type is doing. The only thing that matters is that it should have methods that return an int value to satisfy the interface 'mock'

Implementing shape interface

Code 

Package main
Import ("fmt" "math")


type shape interface 
{
	area() float64
	perimeter()  float64
}
type Rectangle struct
{
	Length  float64
	Breadth  float64
}
type Circle struct
{
	Radius  float64
}
func (A Rectangle) area()  float64
{
	return (A.Length*A.Breadth)
}
func (A Rectangle) perimeter()  float64
{
	return(2* (A.Length+A.Breadth))
}
func(B Circle) area()  float64
{
	return(math.pi*B.radius*B.radius)
}
func(B Circle) perimeter()  float64
{
	return(2*math.pi*B.radius)
}
func main()
{
	var t1 shape
	t1=Rectangle(10,20)
	fmt.Println("Area of rectangle:" , t1.area())
	fmt.Println("Perimeter of rectangle:" , t1.perimeter())
	var  t2 shape
	t2=Circle(3)
	fmt.Println("Area of circle:" , t2.area())
	fmt.Println("Perimeter of circle:" , t2.area())
}

Explanation 

In the above example, we created the interface named ‘shape’ that has got two float64 methods declared in it. Now the functions that are defined as ‘ area() float64 ‘ and ‘perimeter() float64’ will make the interface implement implicitly and the output would be obtained as given below.
 

 

Output 

Area of rectangle:200
Perimeter of rectangle:60
Area of circle:28.27
Perimeter of circle:18.85

Types of Interfaces

Interfaces are of two types - static and dynamic. Static type of interfaces are the normally the interface itself. But just because of the fact that interface does not have a static value, so it always points to the dynamic values. Now coming over to dynamic type interface, if there is a variable  belonging to the interface type that is containing the value of the Type which implements the interface, its called the dynamic type interface or sometimes even concrete value or concrete type.

Example 

package main
import "fmt"

type shape interface {
	area() float64
	perimeter() float64
}
func main() {
	var r shape
	fmt.Println("Value of the shape interface is: ", r)
	fmt.Printf("Type of the shape interface is: %T ", r)
}

Output 

Value of the shape interface is:  <nil>
Type of the shape interface is: <nil>

Explanation 

In the above example, we created the interface named ‘shape’ that has got two float64 methods declared in it.The statement “ fmt.Println("Value of the shape interface is: ", r) “ basically returns the dynamic value of the “ shape “ interface and the second statement “ fmt.Printf("Type of the shape interface is: %T ", r) “ returns the dynamic type.In the output the returned values are both <nil> because the interface “ shape “ doesn’t know who will be implementing it.

Type Assertions

Type Assertion is an operation that is applied to the value of the interface and basically this operation is performed in order to extract the values of the interface. The type assertion operation is used basically to check if the dynamic type of operand matches with the asserted type of operand or not.

Syntax 

f.(T)

Explanation 

Here in the above syntax, “b” is the value of the expression of the interface and “T” is the type which is also known as the asserted type. If “T” is of concrete type then type assertion will check whether the given dynamic type of “f” is equal to “T” or not.

Example 

package main
import "fmt"
func func1(a interface{}) {
	Value := a.(string)
	fmt.Println("Value: ", Value)
}
func main() {
	var Value interface {
} = "It’s_Christmas_Today"
func1(Value)
}

Output 

Value:  It’s_Christmas_Today

Explanation 

In the above example, we pass the string “ It’s_Christmas_Today” and later the function “func1” extracts the value of the interface by the concept of type assertion.
Type Switch

In Go language, type switch is used to compare the dynamic type of interface with different types provided in the case statements. It is very much similar to the type assertion, with the only difference being that type switch is case specific type and not values. In type switch, one can also compare one type to another type of interface.

FAQs

  1.  Is Go language an open-source language?
    • Go language is an open-source programming language that Google has introduced to create simple and reliable software.
  2.  What is Golang useful for?
    • Go language is handy for programming for all kinds of scalable servers and very large software systems.
  3. Is Go language the future of Web Programming?
    • Go language is surely soon going to be the future of web programming because it allows developers to carry out all kinds of functions that other programming languages do individually. So basically, the developer is getting all the different advantages of different languages in a single language.
  4. Can we define an interference type that consists of no functions in it?
    • Go language allows you to create or define interface types that describe no methods and such an interface type is known as an empty interface. Thus any and every method satisfies this empty interface type.
  5. What are some of the most used interface types?
    • Here is a short list of some most common interfaces in the standard library:
      • builtin.Error
      • fmt.Stringer
      • io.Reader
      • io.Writer
      • io.ReadWriteCloser
      • http.ResponseWriter
      • http.Handler

Key Takeaways

This article extensively discussed the Go programming language and the concept of interface types and their implementation. Golang is a programming language that has been developed with the sole purpose of easing off the process of web development and rectifying those issues that a developer faces in the case of Java and C++. Go language offers all those features combined, which all other languages offer individually, and at the same time removes those little flaws that they had. For example, talking about interface types, other languages require the developers to implement the interfaces explicitly, but in the case of Go language interfaces are implicitly implemented. 

We hope that this blog has helped you enhance your knowledge regarding Go interface type and if you would like to learn more, check out our articles on Coding Ninjas Studio.

Do upvote our blog to help other ninjas grow. Happy Coding!

 

Topics covered
1.
Introduction
2.
What Is Go Language?
3.
What are Interfaces and Go Interface Type?
4.
How to create a Go Interface?
4.1.
Syntax 
4.2.
Example 
5.
How are interfaces implemented?
5.1.
For Example 
5.2.
Explanation 
6.
Implementing shape interface
6.1.
Code 
6.2.
Explanation 
6.3.
Output 
7.
Types of Interfaces
7.1.
Example 
7.2.
Output 
7.3.
Explanation 
8.
Type Assertions
8.1.
Syntax 
8.2.
Explanation 
8.3.
Example 
8.4.
Output 
8.5.
Explanation 
9.
FAQs
10.
Key Takeaways