(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");
    }
}

相关推荐
土豆12505 分钟前
Rust 错误处理实战:anyhow + thiserror 的黄金搭档
rust
Zarek枫煜2 小时前
C3 编程语言 - 现代 C 的进化之选
c语言·开发语言·青少年编程·rust·游戏引擎
咚为8 小时前
Rust 经典面试题255道
开发语言·面试·rust
@atweiwei9 小时前
用 Rust 构建 LLM 应用的高性能框架
开发语言·后端·ai·rust·langchain·llm
chrislearn11 小时前
Salvo 为什么不采用宏式路由
rust
Amos_Web1 天前
Solana开发(1)- 核心概念扫盲篇&&扫雷篇
前端·rust·区块链
golang学习记2 天前
VS Code官宣:全面支持Rust!
开发语言·vscode·后端·rust
叹一曲当时只道是寻常2 天前
Tauri v2 + Rust 实现 MCP Inspector 桌面应用:进程管理、Token 捕获与跨平台踩坑全记录
开发语言·后端·rust
怪我冷i2 天前
Rust错误处理之unwrap
rust·cloudflare·unwrap
楚国的小隐士3 天前
为什么说Rust是对自闭症谱系人士友好的编程语言?
java·rust·编程·对比·自闭症·自闭症谱系障碍·神经多样性