Skip to content

Instantly share code, notes, and snippets.

@eloycoto
Created February 22, 2024 07:55
Show Gist options
  • Save eloycoto/a749aeb7d35e38c8c8970c3e5e2dd25e to your computer and use it in GitHub Desktop.
Save eloycoto/a749aeb7d35e38c8c8970c3e5e2dd25e to your computer and use it in GitHub Desktop.
// Controller section
trait EngineController {
fn forward(&self) -> bool {
return true;
}
}
#[derive(Debug)]
struct Engine {}
impl EngineController for Engine {}
#[derive(Debug)]
struct BSC<E: EngineController> {
id: i32,
engine: E,
}
impl<E: EngineController> BSC<E> {
pub fn new(id: i32, engine: E) -> BSC<E> {
BSC {
id: id,
engine: engine,
}
}
// This works, because is a real generic, it has been started from outside.
pub fn take(e: E) -> BSC<E> {
let id = 1;
BSC::new(id, e)
}
// This works, because is the correct type
pub fn take_b() -> BSC<Engine> {
let id = 1;
BSC::new(id, Engine {})
}
// This does not work, the return cannot be a Trait because is defined inside of the implementation
// pub fn take() -> BSC<E> {
// let id = 1;
// let e = Engine {};
// BSC::new(id, e)
// }
}
fn main() {
println!("-----------------------------------------");
let mut res = BSC::new(1, Engine {});
println!("New result is {:?}", res);
println!("-----------------------------------------");
res = BSC::take(Engine {});
println!("take result is {:?}", res);
println!("-----------------------------------------");
res = BSC::<Engine>::take_b();
println!("Take_b result is {:?}", res);
println!("Hello, world!");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment