sách gpt4 ai đã đi

rust - 如何将结构的 Vec 强制转换为特征对象的 Vec?

In lại 作者:行者123 更新时间:2023-11-29 08:13:09 28 4
mua khóa gpt4 Nike

试图创建一个 HashMap 的数据库结构向量。每个VecBao gồm Box .

use std::collections::HashMap;

trait Model {
fn id(&self) -> i32;
}

struct User;
struct Message;

impl Model for User {
fn id(&self) -> i32 { 4 }
}

impl Model for Message {
fn id(&self) -> i32 { 3 }
}

struct DB {
users: Vec<>>,
messages: Vec<>>,
tables: HashMap<>>>,
}

impl DB {
fn new() -> Self {
let users: Vec<>> = Vec::new();
let messages: Vec<>> = Vec::new();
let mut tables: HashMap<>>> = HashMap::new();
tables.insert("users".to_string(), users);
tables.insert("messages".to_string(), messages);
Self {
users,
messages,
tables,
}
}
}

编译器产生以下错误:

   Compiling playground v0.0.1 (/playground)
error[E0308]: mismatched types
--> src/lib.rs:37:44
|
37 | tables.insert("users".to_string(), users);
| ^^^^^ expected trait Model, found struct `User`
|
= note: expected type `std::vec::Vec<>>`
found type `std::vec::Vec<>>`

error[E0308]: mismatched types
--> src/lib.rs:38:47
|
38 | tables.insert("messages".to_string(), messages);
| ^^^^^^^^ expected trait Model, found struct `Message`
|
= note: expected type `std::vec::Vec<>>`
found type `std::vec::Vec<>>`

为什么编译器不能推断出 Người sử dụngMessagehoàn thành Model ?

1 Câu trả lời

类型 BoxBox不可互换。包含一个的集合不能直接转换为另一个,即使使用不安全的代码也是如此。这些类型不同,在内存中有不同的表示。它们甚至有不同的尺寸:

println!("{}", std::mem::size_of::<>>()); // 8
println!("{}", std::mem::size_of::<>>()); // 16

từVec<>> 转换的唯一方法至 Vec<>>是逐项计算的。每个项目都需要这样强制转换:

let model: Box = user;

hoặc:

let model = Box::::from(user);

导致这丑陋的事情:

tables.insert(
"users".to_string(),
người sử dụng
.iter()
.map(|user| Box::::from(user))
.collect()
);

如果在此之后您不需要原始向量,则可以通过使其可变和耗尽来避免克隆:

tables.insert(
"users".to_string(),
người sử dụng
.drain(..)
.map(|user| Box::::from(user))
.collect(),
);

关于rust - 如何将结构的 Vec 强制转换为特征对象的 Vec?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58683548/

28 4 0
行者123
Hồ sơ cá nhân

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá Didi Taxi miễn phí
Mã giảm giá Didi Taxi
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com