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 }
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With