In reading old messages and stuff I came across some mentions of the possibility of interfaces in Nim. I think I must be mis-understanding generics or interfaces or both ?
What do interfaces provide that generic types don't ? Wouldn't an 'interface' in Nim just be a type that implemented the required procedures that gets handed to a procedure accepting a generic? The compiler would complain if you type didn't support the required procedures for the generic right ? (eg if a procedure call Type.foobar() and your type didn't implement foobar() the compiler slaps you?)
Thanks!
With classical proc parameters, the arguments can take variable values.
With proc generic parameters, the generic arguments are now type parameters, and the compiler enforces type checking on the generic type values.
With interfaces, you define some named behaviours that some type must have, and the compiler can check that these names are defined and also do some type (interface) checks. Interfaces are more used in object-oriented languages while Nim is more procedural.
Nim has an experimental concept feature where you can define a set of properties that apply to a type. When used with generic types, concepts should give us more expressive semantic type constraints power that could be checked by the Nim compiler.
Thanks for the detailed reply...I think it helped pinpoint where I'm confused (aside from the runtime thing @mratsim mentioned):
"With interfaces, you define some named behaviours that some type must have, and the compiler can check that these names are defined and also do some type (interface) checks."
Once the compiler knows the concrete type being passed into a proc, it knows what behaviors are available for that type (eg what 'names are defined') and can complain on mis-match. This seemed equivalent to what interfaces provide ( at least in my limited understanding of both generics and interfaces)
@mratsim - thinking about this some more..
"Interfaces are runtime (or compile-time), generics only work at compile-time."
I thought one of the big features of strict type checking was the compiler 'knows'/enforces what types can be passed to a proc at runtime, and can verify they supply all the needed procs/behaviors..
@mratsim , @spip - Thanks again for you replies. It appears I have some basics to google/read up on. Let me get my basics right, and maybe the differences will be more clear.
With interfaces, 1 procedure can handle multiple (n) types input for a parameter, as long as they implement the applicable interface required. With interfaces 1 procedure can return multiple types (n). With generics, it takes n (generated) procedures to handle n different types input as a parameter. With generics it takes n (generated) procedures to return n different types.
I think interfaces are better the higher level you are in the program.
MyInterface product = GetNextProductToProcess()
ProcessProduct(product)
Those two