Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mark golang struct as implementing interface?

Tags:

I have interface:

  type MyInterface interface {   ...   } 

and I want to mark that my struct implements it. I think it is not possible in go, but I want to be certain.

I did the following, but I think it results in an anonymous variable that implements interface. Am I right?

  type MyStruct struct {     ...     MyInterface   } 
like image 945
Sergei G Avatar asked Oct 12 '15 20:10

Sergei G


People also ask

Can a struct implement an interface Golang?

We can define interfaces considering the different actions that are common between multiple types. In Go, we can automatically infer that a struct (object) implements an interface when it implements all its methods.

Can struct implement interface?

A class or struct can implement multiple interfaces, but a class can only inherit from a single class. For more information about abstract classes, see Abstract and Sealed Classes and Class Members. Interfaces can contain instance methods, properties, events, indexers, or any combination of those four member types.

Is a struct an interface Golang?

Structs and interfaces are Go's way of organizing methods and data handling. Where structs define the fields of an object, like a Person's first and last name. The interfaces define the methods; e.g. formatting and returning a Person's full name.

How do you implement an interface in Golang?

Implementing an interface in Go To implement an interface, you just need to implement all the methods declared in the interface. Unlike other languages like Java, you don't need to explicitly specify that a type implements an interface using something like an implements keyword.


1 Answers

In Go, implementing an interface is implicit. There is no need to explicitly mark it as implementing the interface. Though it's a bit different, you can use assignment to test if a type implements an interface and it will produce a compile time error if it does not. It looks like this (example from Go's FAQ page);

type T struct{} var _ I = T{}       // Verify that T implements I. var _ I = (*T)(nil) // Verify that *T implements I. 

To answer your second question, yes that is saying your struct is composed of a type which implements that interface.

like image 108
evanmcdonnal Avatar answered Sep 25 '22 13:09

evanmcdonnal