Swift では、パラメーター等価制約を使用してメソッドをジェネリック型に追加できます。
extension Optional where Wrapped == String {
// Available only for `Optional<String>` type.
func sample1() { ... }
}
Rustでこれを行う方法は?
アップデート
この機能は、ジェネリック Where 句を使用した拡張機能と呼ばれます。
impl
これは基本的に Rust の明示的なトレイトのないwithwhere
句と同じ機能だと思います。
trait OptionUtil {
fn sample1(&self);
}
impl<T> OptionUtil for Option<T> where T:std::fmt::Debug {
fn sample1(&self) {
println!("{:#?}", self);
}
}
(明示的なトレイトなしで) と同等です
extension Optional where Wrapped: DebugDescription {
func sample1() {
print("\(self)")
}
}
ということで、このRustコードで動くと思っていたのですが、エラーで動きません。( 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);
}
}