简体   繁体   中英

How to create new objects of any type that is passed as an argument to a function in Rust

I need to be able to create new objects from any struct that implements some trait, is there a way to achieve that? Right now create_obj accepts objects of struct that implements trait, but in my program I don't have struct objects, they are implemented by user of a library.

trait Tr: {
    fn new() -> Self;
}

struct St {}

impl Tr for St {
    fn new() -> Self {
        Self
    }
}

// I want this function to be able to create any objects (that impl Tr) for me 
fn create_obj<T: Tr>(t: T) -> Box<dyn Tr> {
    Box::new(T::new())
}

#[cfg(test)]
mod tests {
    use crate::{create_obj, St};

    #[test]
    fn it_works() {
        // Here I want to pass a struct type that implements the trait, not the struct object
        create_obj(St);
    }
}

Above code obviously fails with:

^^ help: use struct literal syntax instead: `St {}`

For anyone struggling, here's how I did it:

trait Tr: {
    fn new() -> Self;
}

struct St {}

impl Tr for St {
    fn new() -> Self {
        St {}
    }
}

fn create_obj<U>() -> U
where
   U: Tr
{
    let state = U::new();
    state
}

#[cfg(test)]
mod tests {
    use crate::{create_obj, St};

    #[test]
    fn it_works() {
        create_obj::<St>();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM