首页 > 其他分享 >[Rust] Traits

[Rust] Traits

时间:2024-03-23 17:55:37浏览次数:21  
标签:impl bar String some Traits Rust fn software

Example 1:

trait AppendBar {
    fn append_bar(self) -> Self;
}

impl AppendBar for String {
    fn append_bar(mut self) -> Self {
        self.push_str("Bar");
        return self;
    }
}

fn main() {
    let s = String::from("Foo");
    let s = s.append_bar();
    println!("s: {}", s);
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn is_foo_bar() {
        assert_eq!(String::from("Foo").append_bar(), String::from("FooBar"));
    }

    #[test]
    fn is_bar_bar() {
        assert_eq!(
            String::from("").append_bar().append_bar(),
            String::from("BarBar")
        );
    }
}

 

Example 2

trait AppendBar {
    fn append_bar(self) -> Self;
}

// TODO: Implement trait `AppendBar` for a vector of strings.
impl AppendBar for Vec<String> {
    fn append_bar(mut self) -> Self {
        self.push(String::from("Bar"));
        self
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn is_vec_pop_eq_bar() {
        let mut foo = vec![String::from("Foo")].append_bar();
        assert_eq!(foo.pop().unwrap(), String::from("Bar"));
        assert_eq!(foo.pop().unwrap(), String::from("Foo"));
    }
}

 

Example 3: Default traits

pub trait Licensed {
    fn licensing_info(&self) -> String {
        "Some information".to_string()
    }
}

struct SomeSoftware {
    version_number: i32,
}

struct OtherSoftware {
    version_number: String,
}

impl Licensed for SomeSoftware {} // Don't edit this line
impl Licensed for OtherSoftware {} // Don't edit this line

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn is_licensing_info_the_same() {
        let licensing_info = String::from("Some information");
        let some_software = SomeSoftware { version_number: 1 };
        let other_software = OtherSoftware {
            version_number: "v2.0.0".to_string(),
        };
        assert_eq!(some_software.licensing_info(), licensing_info);
        assert_eq!(other_software.licensing_info(), licensing_info);
    }
}

 

Example 4: Dynmaic traits

pub trait Licensed {
    fn licensing_info(&self) -> String {
        "some information".to_string()
    }
}

struct SomeSoftware {}

struct OtherSoftware {}

impl Licensed for SomeSoftware {}
impl Licensed for OtherSoftware {}

// YOU MAY ONLY CHANGE THE NEXT LINE
fn compare_license_types(software: &dyn Licensed, software_two: &dyn Licensed) -> bool {
    software.licensing_info() == software_two.licensing_info()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn compare_license_information() {
        let some_software = SomeSoftware {};
        let other_software = OtherSoftware {};

        assert!(compare_license_types(&some_software, &other_software));
    }

    #[test]
    fn compare_license_information_backwards() {
        let some_software = SomeSoftware {};
        let other_software = OtherSoftware {};

        assert!(compare_license_types(&other_software, &some_software));
    }
}

 

Example 5: Combine traits

pub trait SomeTrait {
    fn some_function(&self) -> bool {
        true
    }
}

pub trait OtherTrait {
    fn other_function(&self) -> bool {
        true
    }
}

// Define a new trait that requires both SomeTrait and OtherTrait
pub trait CombinedTrait: SomeTrait + OtherTrait {}

// Now, implement CombinedTrait for any struct that implements both SomeTrait and OtherTrait.
impl CombinedTrait for SomeStruct {}
impl CombinedTrait for OtherStruct {}

struct SomeStruct {}
struct OtherStruct {}

impl SomeTrait for SomeStruct {}
impl OtherTrait for SomeStruct {}
impl SomeTrait for OtherStruct {}
impl OtherTrait for OtherStruct {}

// Adjust the function to accept a reference to any object that implements CombinedTrait
fn some_func(item: &dyn CombinedTrait) -> bool {
    item.some_function() && item.other_function()
}

fn main() {
    some_func(&SomeStruct {});
    some_func(&OtherStruct {});
}

 

标签:impl,bar,String,some,Traits,Rust,fn,software
From: https://www.cnblogs.com/Answer1215/p/18091414

相关文章

  • [Rust] Generic
    Example1:fnmain(){letmutshopping_list:Vec<&str>=Vec::new();shopping_list.push("milk");} Example2:structWrapper<T>{value:T,}impl<T>Wrapper<T>{pubfnnew(value:T)->Self{......
  • [Rust] Iter
    Abaisciter:#[test]fnmain(){letmy_fav_fruits=vec!["banana","custardapple","avocado","peach","raspberry"];letmutmy_iterable_fav_fruits=my_fav_fruits.iter();assert_eq!(my_......
  • Rust 的 PhantomData
    在Rust中,PhantomData是一个零大小的标记类型,用于表示泛型参数的某种“幽灵”所有权或依赖性,而不实际持有该类型的数据。它在标准库中的std::marker模块下提供。使用PhantomData的主要场景有:占位以满足泛型约束:有时我们定义了一个泛型结构体,但是并没有直接使用到该......
  • 基于rust的区块链实现
    在开源框架Substrate中构建核心区块链基础设施的初学者友好教程。substrate是一个强大的区块链框架,它允许开发者构建自定义的区块链。Substrate提供了大量的模块化组件,使得开发者可以选择和定制这些组件以满足他们的特定需求,从而极大地加快了区块链开发的速度和灵活性。Subst......
  • Rust Rocket简单入门
    目录简介helloworld常用功能动态路径多个片段(segments)静态文件服务器简单WebAPI示例添加依赖实现接口接口测试参考链接简介Rust中最知名的两个web框架要数Rocket和Actix了,Rocket更注重易用性,Actix则更注重性能。这里只是了解一下Rust下的WebAPI开发流程,就学一下最简单的Rock......
  • Rust 初接触
    官网:https://www.rust-lang.org/Api文档:https://doc.rust-lang.org/std/index.htmlIDE推荐:RustRoverVSCodeVisualStudio主要类型有:https://doc.rust-lang.org/std/index.html#primitivesarrayboolcharf32f64fni8i16i32i64i128isizepointerreference......
  • Rust Package Manager:Cargo
    Cargo是Rust包管理器。Cargo下载您的Rust包的依赖项,编译您的包,制作可分发的包,并将它们上传到crates.io(Rust社区的包注册表)。类似于Python中的pip或Node.js中的npm。Cargo官方文档:TheCargoBook写的十分完美!cargo--list已安装命令:new在当前目......
  • 基于Rust的Tile-Based游戏开发杂记(02)ggez绘图实操
    尽管ggez提供了很多相关特性的demo供运行查看,但笔者第一次使用的时候还是有很多疑惑不解。经过仔细阅读demo代码并结合自己的实践,逐步了解了ggez在不同场景下的绘图方式,在此篇文章进行一定的总结,希望能够帮助到使用ggez的读者。供运行查看,但笔者第一次使用的时候还是有很多疑惑不......
  • 发布 VectorTraits v2.0(支持 x86的Sse系列指令集等)
    目录支持x86的Sse系列指令集为Vector128/Vector256补充全部的向量方法提供CPU型号信息结果范例1:X86CPUonWindows结果范例2:ArmCPUonLinux结果范例3:ArmCPUonMacOS提供所支持的指令集信息结果范例1:X86CPUonWindows结果范例2:ArmCPUonLinux结果范例3:Arm......
  • 简单对比Java、Python、Go、Rust等常见语言计算斐波拉契数的性能
    前言最近简单学了下Rust,以我这种菜鸟水平,没感受到什么安全、性能什么方面的优势,只觉得概念太多,编译各种报错。暂时也写不出来什么玩法,索性对比下各种学过的语言的性能。部分语言很早之前学过,很久不用就忘了,所以是用GPT写的。但运行逻辑很简单,所以应该没什么影响。具体的代码可以......