Rust 学习笔记:关于泛型的练习题

Rust 学习笔记:关于泛型的练习题

Rust 学习笔记:关于泛型的练习题

参考视频:

  1. https://www.bilibili.com/video/BV1JJCVYSEg6

问题 1

答:3。

下面代码能否通过编译?若能,输出是?

rust 复制代码
fn print_slice<T>(v: &[T]) {
    for x in v {
        println!("{}", x);
    }
}

fn main() {
    print_slice(&[1, 2, 3, 4]);
}

答:不能通过编译。T 必须约束为实现了 Display trait 才能 print。

下面代码能否通过编译?若能,输出是?

rust 复制代码
struct Point<T> {
    x: T,
    y: T,
}

impl Point<i32> {
    fn f(&self) -> &i32 {
        &self.y
    }
}

impl<T> Point<T> {
    fn f(&self) -> &T {
        &self.x
    }
}

fn main() {
    let p: Point<i32> = Point { x: 5, y: 10 };
    println!("{}", p.f());
}

答:不能通过编译。因为泛型不可以和具体类型使用同名函数。

相关推荐
SomeOtherTime1 天前
Rust 闭包语法和原理(AI回答)
开发语言·后端·rust
SomeOtherTime1 天前
Rust集合(AI回答)
开发语言·后端·rust
SomeOtherTime2 天前
Rust 泛型与特性讲解(AI回答)
rust
青川Lapis2 天前
RUST:错误处理 thiserror + anyhow 工程化
rust
SomeOtherTime2 天前
Rust生命周期介绍(AI回答)
开发语言·后端·rust
SomeOtherTime3 天前
Rust所有权(AI回答)
开发语言·后端·rust
SomeOtherTime3 天前
Rust 面向对象介绍(AI回答)
开发语言·python·rust
西风测评4 天前
安全的自动更新怎么做:minisign 签名、先验签后解析与防回滚
rust·ssh
Delightrs4 天前
Rust LeetCode238 算法题解
开发语言·算法·rust
奶油话梅糖4 天前
快过 IDM 5 倍、开源免费:4,200 Star 的 Rust 下载器用 7 组对照实验“单挑“行业老大
rust·开源·idm