gpt4 book ai didi

Rust:如何限制派生特征的类型参数

转载 作者:行者123 更新时间:2023-12-03 11:29:55 24 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Lifetime error when creating a function that returns a value implementing serde::Deserialize

(2 个回答)


1年前关闭。




我正在尝试编写一个通用函数,该函数采用指向 csv 文件的路径,将文件解析并反序列化为特定类型的记录向量并返回记录向量。

这是我的代码:

[dependencies]
csv = "1.1"
serde = { version = "1.0", features = ["derive"] }

首先是编译好的特定类型版本:
use csv;
use serde::Deserialize;
use std::path::Path;

#[derive(Debug, Deserialize)]
struct Person {
name: String,
fav_colour: String,
}

#[derive(Debug, Deserialize)]
struct Car {
make: String,
year: u8,
}

fn main() {}

fn parse_csv(file_path: &Path) -> Vec<Person> {
// Create the csv reader
let mut csv_reader = csv::Reader::from_path(file_path).unwrap();

// Parse the csv and collect records
let records: Vec<Person> = csv_reader
.deserialize()
.map(|record: Result<Person, csv::Error>| {
record.expect(&format!("There was a problem parsing a line"))
})
.collect();

// Return records
records
}

parse_csv 函数适用于混凝土 Person结构。

我怎样才能重写这个函数,使它接受一个派生反序列化的泛型类型/结构,例如它可以接受 PersonCar ?

尝试失败:
fn parse_csv<T>(file_path: &Path) -> Vec<T> {
// Create the csv reader
let mut csv_reader = csv::Reader::from_path(file_path).unwrap();

// Parse the csv and collect records
let records: Vec<T> = csv_reader
.deserialize()
.map(|record: Result<T, csv::Error>| {
record.expect(&format!("There was a problem parsing a line"))
})
.collect();

// Return records
records
}

产生:
error[E0277]: the trait bound `for<'de> T: _::_serde::Deserialize<'de>` is not satisfied
--> src/main.rs:26:10
|
26 | .map(|record: Result<T, csv::Error>| {
| ^^^ the trait `for<'de> _::_serde::Deserialize<'de>` is not implemented for `T`
|
help: consider restricting this type parameter with `T: for<'de> _::_serde::Deserialize<'de>`
--> src/main.rs:19:14
|
19 | fn parse_csv<T>(file_path: &Path) -> Vec<T> {
| ^
= note: required because of the requirements on the impl of `_::_serde::de::DeserializeOwned` for `T`
= note: required because of the requirements on the impl of `std::iter::Iterator` for `csv::reader::DeserializeRecordsIter<'_, std::fs::File, T>`


编译器提示:
help: consider restricting this type parameter with `T: for<'de> _::_serde::Deserialize<'de>`

我该怎么做呢?
我对 rust 比较陌生,在阅读了 rust book 的 traits and the where clause 信息后(我怀疑答案在哪里),我仍然无法编译它。

最佳答案

您可以按照以下方式进行操作:

use serde::de::DeserializeOwned;

fn parse_csv<T>(file_path: &Path) -> Vec<T>
where
T: DeserializeOwned,
{
/// deserialization logic
}

关于Rust:如何限制派生特征的类型参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62479410/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com