Welcome To Golang By Example

Menu
  • Home
  • Blog
  • Contact Us
  • Support this website
Menu

Go : Check if type implements an interface

Posted on December 1, 2019December 1, 2019 by admin

Sometimes there can be scenarios where it is needed to know if your type satisfies an interface or not. This can be easily achieved using a blank identifier.

package main

type shape interface {
    getNumSides() int
    getArea() int
}

type square struct {
    len int
}

func (s square) getNumSides() int {
    return 4
}

// func (s square) getArea() int {
//  return s.len * 2
// }

func main() {
    //Verify that *square implement shape
    var _ shape = square{}
}

In the above program, we have commented out the square’s getArea() function. On “go build” above program gives the error

main.go:25:6: cannot use square literal (type square) as type shape in assignment:
        square does not implement shape (missing getArea method)

On uncommenting the getArea() method the error goes away. To check if a pointer of the type implements the interface then it can be done as below

var _ shape = &square{}

OR

var _ shape = (*square)(nil)

First one will give the error

main.go:25:6: cannot use (*square)(nil) (type *square) as type shape in assignment:
        *square does not implement shape (missing getArea method)

while the latter one will give error

main.go:25:6: cannot use &square literal (type *square) as type shape in assignment:
        *square does not implement shape (missing getArea method)
  • go
  • interface
  • type
  • Follow @golangbyexample

    Popular Articles

    Golang Comprehensive Tutorial Series

    All Design Patterns in Go (Golang)

    Slice in golang

    Variables in Go (Golang) – Complete Guide

    OOP: Inheritance in GOLANG complete guide

    Using Context Package in GO (Golang) – Complete Guide

    All data types in Golang with examples

    Understanding time and date in Go (Golang) – Complete Guide

    ©2025 Welcome To Golang By Example | Design: Newspaperly WordPress Theme