У меня есть две структуры, реализующие одну и ту же черту.Мне нужна единственная функция, которая возвращает объект любой из этих структур.
trait
pub trait DbfFile{
fn new(fields: HashMap<String, FieldValue>) -> Self;
}
Структуры
pub struct InsertableAttachable {
pub f1: String,
pub f2: String,
pub f3: String,
pub f4: i8,
}
impl DbfFile for InsertableAttachable{
fn new(fields: HashMap<String, FieldValue, RandomState>) -> Self {
InsertableAttachable {
// fields
}
}
}
// Converting this to generic
impl InsertableAttachable{
pub fn get_data_vector(mut iter: DatabaseRecordIterator) -> Vec<InsertableAttachable>{
let mut db_data: Vec<InsertableAttachable> = vec!();
while let Some(table_row) = iter.next() {
let fields = table_row.fields;
db_data.push(InsertableAttachable::new(fields));
};
db_data
}
}
И еще одна структура
pub struct InsertableAttached {
pub f1: String,
pub f2: i32,
pub f3: i32,
}
impl DbfFile for InsertableAttached {
fn new(fields: HashMap<String, FieldValue, RandomState>) -> Self {
InsertableAttached {
// fields
}
}
}
// Converting this to generic
impl InsertableAttached{
pub fn get_data_vector(mut iter: DatabaseRecordIterator) -> Vec<InsertableAttached>{
let mut db_data: Vec<InsertableAttached> = vec!();
while let Some(table_row) = iter.next() {
let fields = table_row.fields;
db_data.push(InsertableAttached::new(fields));
};
db_data
}
}
Вот пример, подобный , это поле возврата/ struct и этот возвращает параметр.
Следующая функция имеет ошибку времени компиляции
error[E0277]: the size for values of type `(dyn models::traits::DbfFile + 'static)` cannot be known at compilation time
--> src/dbf.rs:75:1
|
75 | / pub fn get_data_vector(&mut iter: DatabaseRecordIterator) -> Vec<DbfFile>{
76 | | let mut db_data: Vec<DbfFile> = vec!();
77 | | while let Some(table_row) = iter.next() {
78 | | let fields = table_row.fields;
... |
81 | | db_data
82 | | }
| |_^ doesn't have a size known at compile-time
|
= help: the trait `std::marker::Sized` is not implemented for `(dyn models::traits::DbfFile + 'static)`
= note: to learn more, visit <https://doc.rust-lang.org/book/ch19-04-advanced-types.html#dynamically-sized-types-and-the-sized-trait>
= note: required by `std::vec::Vec`
error[E0038]: the trait `models::traits::DbfFile` cannot be made into an object
--> src/dbf.rs:75:1
|
75 | pub fn get_data_vector(&mut iter: DatabaseRecordIterator) -> Vec<DbfFile>{
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `models::traits::DbfFile` cannot be made into an object