In Swift, I can add method to a generic type with parameter equality constraint.
extension Optional where Wrapped == String {
// Available only for `Optional<String>` type.
func sample1() { ... }
}
How to do this in Rust?
Update
This feature is called Extensions with a Generic Where Clause.
I think this is basically same feature with Rust's impl
with where
clause without explicit trait.
trait OptionUtil {
fn sample1(&self);
}
impl<T> OptionUtil for Option<T> where T:std::fmt::Debug {
fn sample1(&self) {
println!("{:#?}", self);
}
}
Is equivalent (without explicit trait) to
extension Optional where Wrapped: DebugDescription {
func sample1() {
print("\(self)")
}
}
Therefore, I thought this Rust code would work, but it doesn't work with an error. (equality constraints are not yet supported in where clauses (see #20041)
)
impl<T> OptionUtil for Option<T> where T == String {
fn sample1(&self) {
println!("{:#?}", self);
}
}