RUST impl <T> Wrapper <T>

在自己的 test/expriment 文件夹内,运行:

bash 复制代码
# 1. 创建一个新项目(名字叫 demo)
cargo new demo
cd demo

修改 main.rs 如下:

rust 复制代码
// 1. 定义一个泛型结构体 Wrapper<T>
// T 是泛型参数,可以代表任意类型
struct Wrapper<T> {
    value: T,
}

// 2. 为所有类型 T 实现**通用方法**(所有 T 都能用)
impl<T> Wrapper<T> {
    // 通用方法:获取内部值
    pub fn new(value: T) -> Self {
        Wrapper { value }
    }

    // 通用方法:返回内部值的引用
    pub fn get(&self) -> &T {
        &self.value
    }
}

// 3. 只为 Wrapper<String> 实现**专属方法**
impl Wrapper<String> {
    // 只有 String 类型才能调用这个方法
    pub fn to_uppercase(&self) -> String {
        self.value.to_uppercase()
    }

    // 只有 String 类型能用
    pub fn length(&self) -> usize {
        self.value.len()
    }
}

// 4. 只为 Wrapper<i32> 实现**专属方法**
impl Wrapper<i32> {
    // 只有 i32 类型才能调用
    pub fn double(&self) -> i32 {
        self.value * 2
    }

    pub fn is_positive(&self) -> bool {
        self.value > 0
    }
}

fn main() {
    // ========== 使用 String 版本 ==========
    let s_wrap = Wrapper::new(String::from("hello rust"));
    println!("原始字符串: {}", s_wrap.get());
    println!("大写: {}", s_wrap.to_uppercase()); // ✅ String 专属
    println!("长度: {}", s_wrap.length());      // ✅ String 专属

    // ========== 使用 i32 版本 ==========
    let i_wrap = Wrapper::new(10);
    println!("\n原始数字: {}", i_wrap.get());
    println!("翻倍: {}", i_wrap.double());      // ✅ i32 专属
    println!("是否正数: {}", i_wrap.is_positive()); // ✅ i32 专属

    // 通用方法所有类型都能用
    let b_wrap = Wrapper::new(true);
    println!("\n布尔值: {}", b_wrap.get());
}

在终端运行:

bash 复制代码
# 2. 打开 src/main.rs 文件,把里面内容全删掉,替换成我给你的完整代码
# 3. 运行
cargo run

预期输出:

复制代码
原始字符串: hello rust
大写: HELLO RUST
长度: 10

原始数字: 10
翻倍: 20
是否正数: true

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