共享篋:程序结构和代码解释

  在本节里,了解两个模块mod_baremod_trait结构和代码实现。

学习内容

  • 了解和学习不同结构类型关键词struct实现方法

篇目

基于结构类型的实现

模块mod_bare结构

image

模块mod_bare代码

https://doc.rust-lang.org/stable/error-index.html#E0038

#[derive(Debug, Default, PartialEq)]
pub struct StructType {
    pub data: (u32),
}

impl StructType {
    pub fn get_tuple(&self) -> (u32) {
        (self.data)
    }
}

#[derive(Debug, Default, PartialEq)]
pub struct TupleType (pub u32);

impl TupleType {
    pub fn get_tuple(&self) -> (u32) {
        (self.0)
    }
}

基于衔接特质的实现

模块mod_trait结构

image

模块mod_trait代码

  两个类型的函数new()是通过属性值,实现创建其类型的实例,而特质方法get_object()是通过其类型本身实例,实现创建一个新的类型实例。

pub mod mod_bare;
pub mod mod_where_fn;
pub mod mod_static_fn;
pub mod mod_box_static_fn;
pub mod mod_dynamic_fn;
pub mod mod_box_dynamic_fn;

pub mod mod_trait {
    #[derive(Debug, Default, PartialEq, Copy, Clone)]
    pub struct StructType {
        data: (u32),
    }

    #[derive(Debug, Default, PartialEq, Copy, Clone)]
    pub struct TupleType(pub u32);

    pub trait TraitCanal {
        fn get_object(&self) -> Self where Self: Sized;  // For keyword `dyn`
        //fn get_object(&self) -> Self;                  // E0038 For keyword `dyn`; OK for static functions
        fn get_tuple(&self) -> (u32);
    }

    impl TraitCanal for StructType {
        fn get_object(&self) -> Self {
            StructType{data: self.data}
        }

        fn get_tuple(&self) -> (u32) {
            println!("impl TraitCanal for StructType");
            (self.data)
        }
    }

    impl TraitCanal for TupleType {
        fn get_object(&self) -> Self {
            TupleType(self.0)
        }

        fn get_tuple(&self) -> (u32) {
            println!("impl TraitCanal for TupleType");
            (self.0)
        }
    }

    impl StructType {
        pub fn new(_data: u32) -> Self {
            StructType{data: _data}
        }
    }

    impl TupleType {
        pub fn new(_data: u32) -> Self {
            TupleType(_data)
        }
    }
}

题外话

学习理解编译错误

  在程序文件src/lib.rs里,使用关键词trait定义衔接特质TraitCanal代码块的第一行代码注释掉,而第二行代码去掉注释,一旦执行编译,就会出现下面错误信息:error[E0038]

error[E0038]: the trait `mod_trait::TraitCanal` cannot be made into
an object
--> lib-hello/src/mod_dynamic_fn.rs:4:1
|
4 | pub fn get_dynamic_trait_ref(canal: &dyn TraitCanal) -> (u32) {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ t
he trait `mod_trait::TraitCanal` cannot be made into an object
|
= note: method `init` references the `Self` type in its arguments
or return type

  下面链接里的E0038就是该错误编号,点击下面链接就可以了解到错误的原因信息。

https://doc.rust-lang.org/stable/error-index.html#E0038

参考资料