(done) 速通 rustlings(22) 泛型

泛型例子

RUST 中最典型的利用了泛型的例子就是 Vec,它可以装任何数据类型,如下:

rust 复制代码
// `Vec<T>` is generic over the type `T`. In most cases, the compiler is able to
// infer `T`, for example after pushing a value with a concrete type to the vector.
// But in this exercise, the compiler needs some help through a type annotation.

fn main() {
    // TODO: Fix the compiler error by annotating the type of the vector
    // `Vec<T>`. Choose `T` as some integer type that can be created from
    // `u8` and `i8`.
    let mut numbers = Vec::<i32>::new();

    // Don't change the lines below.
    let n1: u8 = 42;
    numbers.push(n1.into());
    let n2: i8 = -1;
    numbers.push(n2.into());

    println!("{numbers:?}");
}

泛型实现

以下是我们自己实现泛型的一个例子:

rust 复制代码
// This powerful wrapper provides the ability to store a value of any type.
// We rewrite it using a generic so that it supports wrapping ANY type `T`.
struct Wrapper<T> {
    value: T,
}

// Adapt the struct's implementation to be generic over the wrapped value.
impl<T> Wrapper<T> {
    fn new(value: T) -> Self {
        Wrapper { value }
    }
}

fn main() {
    // You can optionally experiment here.
}

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

    #[test]
    fn store_u32_in_wrapper() {
        assert_eq!(Wrapper::new(42).value, 42);
    }

    #[test]
    fn store_str_in_wrapper() {
        assert_eq!(Wrapper::new("Foo").value, "Foo");
    }
}

相关推荐
星栈12 小时前
用 Rust + Makepad 做一个 JSON 查看器:从零到能用的全过程
前端·rust
日取其半万世不竭13 小时前
Rust《腐蚀》 服务器低成本怎么开?配置、端口和存档避坑
服务器·开发语言·rust
techdashen14 小时前
Cargo 1.93 开发周期动态全解析
rust
Vallelonga14 小时前
Rust 中的枚举
开发语言·rust
薛定谔的猫-菜鸟程序员14 小时前
从Electron到Tauri,Rust+Vue(Tauri) 实现超高性能桌面日志应用开发,以及开发避坑指南
vue.js·rust·electron
不爱学英文的码字机器1 天前
[鸿蒙PC命令行移植适配]移植rust三方库bottom到鸿蒙PC的完整实践
华为·rust·harmonyos
W_LuYi1851 天前
Tauri + Rust + Vue 3 打造极速轻量桌面应用
java·开发语言·vue.js·rust
星栈1 天前
Makepad 界面怎么做得更像产品,而不是示例
前端·rust
特立独行的猫a2 天前
MQTT Client的Tauri应用移植到 OpenHarmony 鸿蒙 PC/ARM64 实践记录
mqtt·华为·rust·harmonyos·tauri·移植·鸿蒙pc