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.
Go
package main
import (
"fmt"
"math"
)
// Define the interface
type Shape interface {
Area() float64
Perimeter() float64
}
// Circle type that implements the Shape interface
type Circle struct {
radius float64
}
// Rectangle type that implements the Shape interface
type Rectangle struct {
length, width float64
}
func (c Circle) Area() float64 {
return math.Pi * c.radius * c.radius
}
func (c Circle) Perimeter() float64 {
return 2 * math.Pi * c.radius
}
func (r Rectangle) Area() float64 {
return r.length * r.width
}
func (r Rectangle) Perimeter() float64 {
return 2 * (r.length + r.width)
}
// Main function to demonstrate the interface
func main() {
var s Shape
s = Circle{radius: 5}
fmt.Println("C Area:", s.Area())
fmt.Println("C Perimeter:", s.Perimeter())
s = Rectangle{length: 4, width: 3}
fmt.Println("R Area:", s.Area())
fmt.Println("R Perimeter:", s.Perimeter())
}
OutputC 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.
Go
package main
import "fmt"
type Shape interface {
Area() float64
}
func main() {
var s Shape
fmt.Println("Value of s:", s) // nil
fmt.Printf("Type of s: %T\n", s) // <nil>
}
OutputValue 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
Go
package main
import "fmt"
func printArea(s interface{}) {
value, ok := s.(Shape)
if ok {
fmt.Println("Area:", value.Area())
} else {
fmt.Println("Not a Shape interface")
}
}
type Shape interface {
Area() float64
}
type Square struct {
side float64
}
func (s Square) Area() float64 {
return s.side * s.side
}
func main() {
sq := Square{side: 4}
printArea(sq)
}
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:
Go
package main
import (
"fmt"
"math"
)
type Circle struct {
radius float64
}
type Rectangle struct {
length, width float64
}
func (c Circle) area() float64 {
return math.Pi * c.radius * c.radius
}
func (r Rectangle) area() float64 {
return r.length * r.width
}
// Function to determine the type of shape and calculate area
func calculateArea(shape interface{}) {
switch s := shape.(type) {
case Circle:
fmt.Printf("Circle area: %.2f\n", s.area())
case Rectangle:
fmt.Printf("Rectangle area: %.2f\n", s.area())
default:
fmt.Println("Unknown shape")
}
}
func main() {
c := Circle{radius: 5}
r := Rectangle{length: 4, width: 3}
calculateArea(c)
calculateArea(r)
}
OutputCircle area: 78.54
Rectangle area: 12.00
Similar Reads
Scope of Variables in Go Prerequisite: Variables in Go Programming Language The scope of a variable defines the part of the program where that variable is accessible. In Go, all identifiers are lexically scoped, meaning the scope can be determined at compile time. A variable is only accessible within the block of code where
2 min read
Go Decision Making (if, if-else, Nested-if, if-else-if) Decision making in programming is similar to decision making in real life. In decision making, a piece of code is executed when the given condition is fulfilled. Sometimes these are also termed as the Control flow statements. Golang uses control statements to control the flow of execution of the pro
5 min read
Loops in Go Language Go language contains only a single loop that is for-loop. A for loop is a repetition control structure that allows us to write a loop that is executed a specific number of times. In Go language, this for loop can be used in the different forms and the forms are: 1. As simple for loop It is similar t
5 min read
Loop Control Statements in Go Language Loop control statements in the Go language are used to change the execution of the program. When the execution of the given loop left its scope, then the objects that are created within the scope are also demolished. The Go language supports 3 types of loop control statements: Break Goto Continue Br
3 min read
Switch Statement in Go In Go, a switch statement is a multiway branch statement that efficiently directs execution based on the value (or type) of an expression. There are two main types of switch statements in Go:Expression SwitchType SwitchExamplepackage mainimport "fmt"func main() { day := 4 switch day { case 1: fmt.Pr
2 min read
Arrays in Go Arrays in Golang or Go programming language is much similar to other programming languages. In the program, sometimes we need to store a collection of data of the same type, like a list of student marks. Such type of collection is stored in a program using an Array. An array is a fixed-length sequen
7 min read
Slices in Golang Slices in Go are a flexible and efficient way to represent arrays, and they are often used in place of arrays because of their dynamic size and added features. A slice is a reference to a portion of an array. It's a data structure that describes a portion of an array by specifying the starting index
14 min read
Functions in Go Language In Go, functions are blocks of code that perform specific tasks, which can be reused throughout the program to save memory, improve readability, and save time. Functions may or may not return a value to the caller.Example:Gopackage main import "fmt" // multiply() multiplies two integers and returns
3 min read
Structures in Golang A structure or struct in Golang is a user-defined type that allows to group/combine items of possibly different types into a single type. Any real-world entity which has some set of properties/fields can be represented as a struct. This concept is generally compared with the classes in object-orient
7 min read
Packages in Golang Packages are the most powerful part of the Go language. The purpose of a package is to design and maintain a large number of programs by grouping related features together into single units so that they can be easy to maintain and understand and independent of the other package programs. This modula
5 min read