Created
November 25, 2021 15:23
-
-
Save pidb/d5094570442b1b8301802ad7a1be48e7 to your computer and use it in GitHub Desktop.
[rust] References to traits in structs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// see https://stackoverflow.com/questions/26212397/references-to-traits-in-structs | |
#![allow(unused)] | |
use std::borrow::Borrow; | |
trait Type { | |
fn type_to_string(&self) -> String; | |
} | |
struct BoolType {} | |
impl Type for BoolType { | |
fn type_to_string(&self) -> String { | |
String::from("BOOL") | |
} | |
} | |
struct IntType {} | |
impl Type for IntType { | |
fn type_to_string(&self) -> String { | |
String::from("INT") | |
} | |
} | |
struct TypeInstance { | |
types: [Box<dyn Type + 'static>; 2], | |
} | |
impl TypeInstance { | |
fn new() -> Self { | |
Self { | |
types: [Box::new(BoolType{}), Box::new(IntType{})], | |
} | |
} | |
fn get_bool_instance(&self) -> &dyn Type { | |
self.types[0].borrow() | |
} | |
fn get_int_instance(&self) -> &dyn Type { | |
self.types[1].borrow() | |
} | |
} | |
fn main() { | |
let TYPE_INSTANCE: TypeInstance = TypeInstance::new(); | |
println!("{}", TYPE_INSTANCE.get_bool_instance().type_to_string()); | |
println!("{}", TYPE_INSTANCE.get_int_instance().type_to_string()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment