Sobes.tech
Middle

How to verify compliance of a structure with an interface in Go?

sobes.tech AI

Answer from AI

In Go, interface compliance is checked implicitly at compile time. If a struct implements all the methods required by an interface, it is automatically considered to satisfy that interface. Explicit declaration of compliance is not required.

You can use the following techniques to verify compliance at compile time:

  1. Assigning a variable of interface type.
  2. Passing the struct to a function expecting an argument of interface type.

Example with assignment:

// Define the interface
type MyInterface interface {
	DoSomething()
	GetValue() int
}

// Define the struct that should satisfy the interface
type MyStruct struct {
	value int
}

// Methods of the struct implementing MyInterface
func (s MyStruct) DoSomething() {
	// some logic
}

func (s MyStruct) GetValue() int {
	return s.value
}

// Check compliance at compile time:
// Assign an instance of the struct to a variable of interface type.
// If MyStruct does not implement MyInterface, the compiler will produce an error.
var _ MyInterface = MyStruct{}

Example with passing to a function:

// Function accepting an argument of interface type MyInterface
func Process(item MyInterface) {
	item.DoSomething()
	_ = item.GetValue() // use the value
}

// Elsewhere in the code:
// Create an instance of MyStruct
myInstance := MyStruct{value: 42}

// Pass the struct instance to a function expecting an interface.
// If MyStruct does not implement MyInterface, the compiler will produce an error.
Process(myInstance)

These approaches ensure that the struct satisfies the specified interface even before running the program, which is an important aspect of type safety in Go.