< 返回版块

ULD 发表于 2019-10-15 01:48

Tags:泛型,Generic,serde

struct Person {
    name: String,
}

pub struct Message<T> (pub T);

impl<T> Message<T> {
    /// 测试1
    pub fn ok() -> Self {
        // 报错
        Self::new(Person {
            name: "Sam".to_owned(),
        })
    }

    pub fn new(data: T) -> Self {
        Self(data)
    }
}

/// 测试2
pub fn ok() {
    // 正常
    Message::new(Person {
        name: "Sam".to_owned(),
    });
}

测试2代码块正常,测试1代码块会报错,报错内容如下:

mismatched types

expected type parameter, found struct `Person`

note: expected type `T`
         found type `Person`rustc(E0308)
message.rs(14, 19): expected type parameter, found struct `Person`

RUST版本1.38.0

怎样修改才能使测试1代码块不报错?求指教,感谢!

评论区

写评论
作者 ULD 2019-10-15 14:42

感谢@yinyanlv,原来是返回类型的问题,明白了

yinyanlv 2019-10-15 10:21
#[derive(Debug)]
pub struct Person {
    name: String,
}

#[derive(Debug)]
pub struct Message<T> (pub T);

impl<T> Message<T> {
    /// 测试1
    pub fn ok() -> Message<Person> {
        // 报错
        // Self == Message<T> != Message<Person>,T != Person
        // Self::new == Message<T>::new,这种写法是不是问题?因为关联函数调用一般是Message::<T>::new
        Message::new(Person {
            name: "Sam2".to_owned(),
        })
    }

    pub fn new(data: T) -> Self {
        Self(data)
    }
}

/// 测试2
fn ok() -> Message<Person>{
    // 正常
    Message::new(Person {
        name: "Sam1".to_owned(),
    })
}

fn main() {

    let a = ok();
    let b = Message::<Person>::ok();
    let c = Message::<Person>::new(Person {
        name: "Sam3".to_owned(),
    });

    println!("{:?}", a);
    println!("{:?}", b);
    println!("{:?}", c);
}

作者 ULD 2019-10-15 01:51

卡住了,发了两遍-_-!

1 共 3 条评论, 1 页