Idomatic way to use "template method" pattern

Good morning,

is using the template method pattern in Rust idiomatic?

It works using traints and default implementations, but is this the idiomatic way or does this rather go into "you can write Fortran in any language" direction?

Thank you!

This is idiomatic, many well used and powerful traits in Rust (i.e. Iterator) provide default implementations for some (or most) of their exposed methods.

This is different because default methods allow overriding while the "template method pattern" doesn't. So it's more like an extension trait with a blanket implementation. Rng is an example.

This has been irking me: many Iterator methods should not really be part of the trait because you don't really want them to be customized to do something else.

You could argue that allowing customization does no harm, but I disagree. Smaller APIs are better.

1 Like

Ah, I wasn't aware. Thanks for clarifying. Then extension traits with blanket implementations do sound like they are more akin to the template method pattern compared to traits with provided methods.

Other examples are the extension traits from the futures crates, i.e. StreamExt or FutureExt.

Thank you. This is leading me into a good direction.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.