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

相关推荐
红尘散仙5 小时前
一个 `#[uniffi::export]`,把 Rust 接进 React Native
前端·后端·rust
红尘散仙5 小时前
一行 `#[specta::specta]`,让 Tauri IPC 有类型
前端·后端·rust
codealy15 小时前
Rust 核心理论与内存安全(一)
后端·安全·rust
土豆.exe17 小时前
IfAI v0.5.0 深度技术解析:120,000 行 Rust 打造的 AI-Native 编辑器
rust·编辑器·ai-native
咸甜适中17 小时前
rust语言学习笔记Trait之 AsRef 和 AsMut(引用转换)
笔记·学习·rust
XD74297163618 小时前
科技早报晚报|2026年5月18日:Agent 原生语言、代码语义图谱与 Rust 数据层,今天更值得跟进的 3 个技术机会
开发语言·科技·rust·科技新闻·开发者工具·ai工程
yezipi耶不耶18 小时前
讲讲 RTMate (WebSocket as A Service)中的消息的发布订阅机制
websocket·网络协议·rust
五月君_1 天前
Bun v1.3.14 发布,Rust 版即将进 Claude Code 内测,下一版可能就告别 Zig
开发语言·后端·rust
techdashen1 天前
深入 Rust enum 的内存世界
开发语言·后端·rust
techdashen1 天前
Rust 模块和文件不是一回事:一次讲清 `mod`、`use`、`pub use`
开发语言·后端·rust