Hello,
I wrote the bellow code.
My intention is to store a vec of generic struct (Metric) and retrieve each item afterwards. If possible with the original type they were created with.
Below code works fine. But I would like the get_mes() method to return T from Metric field mes and not a String.
use std::fmt::Debug;
#[derive(Debug)]
struct Metric<T> {
name: String,
mes: T,
}
trait Measure {
fn get_name(&self) -> String;
fn get_mes(&self) -> String;
}
impl Measure for Metric<usize> {
fn get_name(&self) -> String {
self.name.clone()
}
fn get_mes(&self) -> String {
self.mes.to_string()
}
}
impl Measure for Metric<f32> {
fn get_name(&self) -> String {
self.name.clone()
}
fn get_mes(&self) -> String {
self.mes.to_string()
}
}
impl Debug for dyn Measure {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "Metric{{name:{}, mes:{}}}", self.get_name(),self.get_mes())
}
}
fn main() {
let mut data: Vec<Box<dyn Measure>> = Vec::new();
data.push(Box::new(Metric {
name: String::from("titi"),
mes: 12,
}));
data.push(Box::new(Metric {
name: String::from("toto"),
mes: 0.2,
}));
println!("{:?}", data[0].get_mes());
println!("{:?}", data);
}
So I changed my code to this one : Rust Playground
And to be honest I don't know how to get out of these errors.
I have the feelings that it is not possible to return the original T type. Can you confirm ?
Is there a way to achieve what I would like to do ?