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

相关推荐
第一程序员10 小时前
Rust trait 入门:把 AI 客户端抽象成可替换接口
python·rust·github
分布式存储与RustFS11 小时前
RustFS Beta.10 性能解读:PUT 全面反超 MinIO,Rust 重写对象存储成了?
开发语言·后端·rust
l1t13 小时前
测试用rust重写的postgresql: pgrust
开发语言·postgresql·rust
@atweiwei15 小时前
Langchainrust:中LLM-as-a-Judge,用 Rust 实现一套 LLM 评估系统
开发语言·后端·ai·rust·llm·rag
程序员爱钓鱼18 小时前
Rust match 模式匹配详解:比 if 更强大的条件分支
后端·rust
爱吃牛肉的大老虎1 天前
rust基础之环境搭建
java·开发语言·rust
openKylin1 天前
与全球技术演进同频,openKylin 3.0从C迈向Rust
c语言·开发语言·rust·开源·开放原子·openkylin
Source.Liu1 天前
【A11】Duration —— 精确时长结构体实现
rust·time
右耳朵猫AI_2 天前
用 Rust 重写 Bun
rust·bun
独孤留白2 天前
Rust 可变性完整指南 —— 从默认不可变到多线程安全修改
rust