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

相关推荐
土豆12501 天前
Rust宏编程完全指南:用元编程解锁Rust的终极力量
rust·编程语言
小杍随笔1 天前
【Rust 语言编程知识与应用:基础数据类型详解】
开发语言·后端·rust
小杍随笔1 天前
【Rust 语言编程知识与应用:自定义数据类型详解】
开发语言·后端·rust
咚为1 天前
Rust 跨平台编译实战:从手动配置到 Cross 容器化
开发语言·后端·rust
幸福指北2 天前
我用 Tauri + Vue 3 + Rust 开发了一款跨平台网络连接监控工具Portview,性能炸裂!
前端·网络·vue.js·tcp/ip·rust
咚为2 天前
深入浅出 Rust FFI:从内存安全到二进制兼容
开发语言·安全·rust
a1117762 天前
剪切板助手TieZ(开源项目rust)
rust·开源·剪切板
盒马盒马2 天前
Rust:迭代器
开发语言·后端·rust
Source.Liu3 天前
【Iced】stream.rs文件
rust·iced
Kapaseker3 天前
精通 Rust 宏 — 包装新类型
rust