Option<Self> を返す trait を実装したかったがRustコンパイラ君が賢すぎただけの日記

trait OptionalConstructor {
    fn optional_new() -> Option<Self>;
    //                   ^^^^^^^^^^^^ doesn't have a size known at compile-time
    //                   Option<Self> where Self: Sized;
}
   Compiling playground v0.0.1 (/playground)
error[E0277]: the size for values of type `Self` cannot be known at compilation time
   --> src/main.rs:2:26
    |
2   |     fn optional_new() -> Option<Self>;
    |                          ^^^^^^^^^^^^ doesn't have a size known at compile-time
    |
help: consider further restricting `Self`
    |
2   |     fn optional_new() -> Option<Self> where Self: Sized;
    |                                       ^^^^^^^^^^^^^^^^^

記事にしようと思ったけどコンパイラ君が丁寧に書いてくれたので特に書くことなかった...、Self が lifetime parameterを取る場合もこのように書ける

trait OptionalConstructor {
    fn optional_new() -> Option<Self> where Self: Sized ;
}

struct S<'a> {
    s: &'a str
}

impl<'a> OptionalConstructor for S<'a>{
    fn optional_new() -> Option<Self> {
        None
    }
}

fn main() {}

ちなみに自分でOptionもどきを実装しても同じような事を言われる、Rustコンパイラ君賢すぎる...