Today's Question:  What does your personal desk look like?        GIVE A SHOUT

How to check whether a struct implements an interface in GoLang

  sonic0002        2020-05-03 00:05:54       19,049        0    

Unlike other programming languages like Java, when implementing an interface in GoLang, there is no syntax like below to explicit tell the relationship:

type I interface {
}

type A struct implements I {
}

When looking at the code or running the code in GoLang, it might lead to a case one doesn't know whether a struct implements interface before trying to use it as some interface.

According to GoLang spec, as long as a struct implements all functions of an interface, it is considered as having implemented that interface and can be used wherever that interface is expected.

To check whether a struct implemented some interface, below similar code can be written in program.

var _ I = new(A)

Here I is the interface, A is the struct type to be checked. If A implements interface I, there will be no compilation error when building the program, otherwise it will throw compilation error like below.

package main

// I interface
type I interface {
	Print()
}

// A ...
type A struct {
}

func main() {
	var _ I = new(A)
}

// # command-line-arguments
// .\main.go:13:6: cannot use new(A) (type *A) as type I in assignment:
//         *A does not implement I (missing Print method)

So if you want to verify whether one struct implements an interface before using it as an interface, above method can be used. The new() function will only allocate memory and set the value to 0 which takes few memory and can be GCed easily. 

In fact, many open source libraries have used such mechanism to check interface implementation.

IMPLEMENTATION  CHECK  INTERFACE  GOLANG 

Share on Facebook  Share on Twitter  Share on Weibo  Share on Reddit 

  RELATED


  0 COMMENT


No comment for this article.