This page is under active revision, content may be updated without notice
Golang implements interfaces as types and as collection of methods(specs for what should be considered of that type). Let’s first talk about collection of methods (specs that other types could implement)
SO here we creted a slice of type Vehicle and stuffed our structs implementing Vehicle, ieterating over them easily. If we assign type that does not implements, methods in Vehicle interface it can not be included in slice, let’s look at it
typeJumbostruct {}funcmain(){ vehicles := []Vehicle{ Car{ 100 }, Car{ 110 }, Bike{ 70 }, Truck{ 60 }, Jumbo{} }for _, vehicle :=range vehicles { fmt.Println(vehicle.Start()) fmt.Println(vehicle.Speed()) fmt.Println(vehicle.Stop()) }}// cannot use Jumbo literal (type Jumbo) as type Vehicle in array element: // Jumbo does not implement Vehicle (missing Run method)
So this clearly not going to accept Jumbo in Vehicle slice as it does not implement Vehicle
Now we come to the next use of interface, that is type. In function’s argument signature can accept an interface type, meaning it could accept any type of value as those can be converted/casted to interface
funcPrintInterface( value interface{} ){ fmt.Println(value)}funcmain(){PrintInterface( 80 )PrintInterface( "apple" )PrintInterface( 90.10 )PrintInterface( []string{"a", "b", "c", "d"} )}// 80// apple// 90.1// [a b c d]