LoginSignup
0
0

More than 1 year has passed since last update.

generics覚書

Posted at

structでgenericsを使う際にどういう定義をしたらよいか
迷ってChatGPT先生に教えていただいたので覚書。
また、得られた自由な型をFromトレイトを使ってどう定義すれば
よいかもChatGPT先生にお伺いした。

#[derive(Debug)]
struct MyStruct<T> {
    my_val: T,
}

impl<T> MyStruct<T> {
    fn new(val: T) -> Self {
        Self {
            my_val: val,
        }
    }
}

impl<T> From<&'static str> for MyStruct<T>
where
    T: From<&'static str>,
{
    fn from(s: &'static str) -> Self {
        Self::new(T::from(s))
    }
}

impl<T> From<String> for MyStruct<T>
where
    T: From<String>,
{
    fn from(s: String) -> Self {
        Self::new(T::from(s))
    }
}

fn main() {
    let struct1: MyStruct<&str> = MyStruct::from("string: &str");
    let struct2: MyStruct<String> = MyStruct::from(String::from("string: String"));

    println!("{struct1:?}");
    println!("{struct2:?}");
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0