SoFunction
Updated on 2025-03-05

Two ways to transform interface objects in golang

There are two ways to transform interface objects:

1. Method 1: instance, ok:= interface object. (actual type)

If the interface object is the corresponding actual type, then instance is the object after transformation, and the value of ok is true
Use with if...else if...

2. Method 2:

Interface object.(type)
Used in conjunction with switch...case statement

Example:

package main
 
import (
    "fmt"
    "math"
)
 
type shape interface {
    perimeter() int
    area() int
}
 
type rectangle struct {
    a int  // long    b int  // Width}
func (r rectangle) perimeter() int {
    return ( + ) * 2
}
func (r rectangle) area() int {
    return  * 
}
 
type circle struct {
    radios int
}
func (c circle) perimeter() int {
    return 2 *  * int(())
}
func (c circle) area() int {
    return int(((float64(), 2) * ))
}
 
func getType(s shape) {
    if i, ok := s.(rectangle); ok {
        ("The length of the rectangle: %d, the width of the rectangle is: %d\n", , )
    } else if i, ok := s.(circle); ok {
        ("The radius of the circle is: %d\n", )
    }
}
 
func getType2(s shape) {
    switch i := s.(type) {
    case rectangle:
        ("The length of the rectangle: %d, the width of the rectangle is: %d\n", , )
    case circle:
        ("The radius of the circle is: %d\n", )
    }
}
 
func getResult(s shape) {
    ("The perimeter of the graph is: %d, and the area of ​​the graph is: %d\n", (), ())
}
 
func main() {
    r := rectangle{a: 10, b: 20}
    getType(r)
    getResult(r)
 
    c := circle{radios: 5}
    getType2(c)
    getResult(c)
}

The above example uses Method 1. If you want to use Method 2, you can change the getType() function to:

func getType(s shape) {
 switch i := s.(type) {
 case rectangle:
  ("The length of the graph: %.2f, the width of the graph: %.2f \n", , )
 case triangle:
  ("The first edge of the graph: %.2f, the second edge of the graph: %.2f, the third edge of the graph: %.2f \n",,,)
 case circular:
  ("Radius of the graph: %.2f \n",)
 }
}

PS: The above is used to calculate the area of ​​a triangle. The formula is:

The area of ​​a triangle = square root [half of the triangle circumference × (half of the triangle circumference minus the first edge) × (half of the triangle circumference minus the second edge) × (half of the triangle circumference minus the third edge)]

This is the end of this article about the transformation of interface objects in golang. For more related contents of golang interface objects, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!