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 (MyFunc in 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 w has method write, and it does what write_data expects (takes in certain args and returns certain values, aka, method signature), w can be passed in to write_data
  • the emphasis is not on “what class w is”, is instead on “does w have write method”

up

down

reference