I have been writing C# code for 10 years, but I am woefully weak on knowing exactly when to use an interface vs. using a Func or Action. It seems to me that in many places where a method on an interface is called, a Func or Action would work just as well. So, I guess my question is this. If I have an interface with just a single method, or perhaps a couple methods, is there any disadvantage to using a Func or Action instead? Using a Func or Action seems cleaner to me.
Thanks very much.
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.
Interfaces in GO Interface are the custom type that is used to specify a set of one or more method signatures which are allowed to create a variable of an interface type and this variable can be assigned with a concrete type value that has the methods the interface requires.
In Java 8, the equivalents are the java. util. function. Function<T, R> and java.
I guess you can compare an Action
or Func
with an interface containing one method, with the difference that you can supply any Action
or Func
that meets the parameter / return value requirements, where when using interfaces, the supplied object must implement that interface.
Perhaps you could call Action
and Func
"anonymous single method interfaces".
If you look at the design perspective though, your class model would be a drawing of blocks without any lines between them.
You should use delegates and lambda expressions if the implementations are expected to be very short (one or two lines), and especially if the implementations are expected to need local variables (closures).
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