how to use interface

tags: learning go programming

content

go-interface-basics-2#4eab6c

  • in the above code, both Book and Count implement fmt.Stringer interface, although they’re completely different things

  • if we have the below function:

func WriteLog(s fmt.Stringer) {
	log.Println(s.String())
}
  • we will be able to pass Book and Count as argument to the function, everything would work!
book := Book{Title: "test", Author: "test"}
WriteLog(book)  // this line works!

Note

for a function’s argument, it’s varName varType.
in the case of WriteLog, it’s s fmt.Stringer, so remember, interface is just another type!
when an interface being declared, it’s (type MyInterface interface).

up

down

reference