What does it mean when a function takes an interface as arguments?
tags: learning go programming
content
type MyInterface interface {
MyFunc()
}
// ...something...
func DoSomething(i MyInterface) {
i.MyFunc()
}what does it mean when a function takes an interface as arguments like above?
-
when a function takes interfaces as arguments, it’s basically saying:
- “i don’t care what you are, as long as you can do certain things”
- what you are → what the object is (interface/struct/other types)
- do certain things → the object has the method to call (
MyFuncin this example)
-
an interface is just a collection of function signatures
- so when a function takes interfaces as args, it’s expecting to call those functions
- as long as an interface has the methods that could be potentially called in the function, the interface can be passed in
-
in python, the analogy would be something like:
class Writer:
# something
def write(self, data):
# something
def write_data(w: writer, data):
w.write(data)- as long as
whas methodwrite, and it does whatwrite_dataexpects (takes in certain args and returns certain values, aka, method signature),wcan be passed in towrite_data - the emphasis is not on “what class
wis”, is instead on “doeswhavewritemethod”