VOOZH about

URL: https://www.geeksforgeeks.org/go-language/interfaces-in-golang/

⇱ Interfaces in Golang - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Interfaces in Golang

Last Updated : 28 Oct, 2024

In Go, an interface is a type that lists methods without providing their code. You can’t create an instance of an interface directly, but you can make a variable of the interface type to store any value that has the needed methods.

Example

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

In this example, Shape is an interface that requires any type implementing it to have Area and Perimeter methods.

Syntax

type InterfaceName interface {
Method1() returnType
Method2() returnType
}

How to Implement Interfaces

In Go, to implement an interface, a type must define all methods declared by the interface. Implementation is implicit, meaning no keyword (such as implements) is needed.


Output
C Area: 78.53981633974483
C Perimeter: 31.41592653589793
R Area: 12
R Perimeter: 14

Dynamic Values

An interface can hold any value, but the actual value and its type are stored dynamically.


Output
Value of s: <nil>
Type of s: <nil>

Here, since s is unassigned, it shows <nil> for both value and type.

Interfaces Types

Type Assertion

Type assertion allows extracting the underlying type of an interface.

Syntax

value := interfaceVariable.(ConcreteType)

Example


Output
Area: 16

Type Switch

A type switch can be used to compare the dynamic type of an interface against multiple types.

Syntax

switch variable.(type) {
case type1:
// Code for type1
case type2:
// Code for type2
default:
// Code if no types match
}

Example:


Output
Circle area: 78.54
Rectangle area: 12.00
Comment
Article Tags:

Explore