Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use std::fmt;
- enum ContainedType {
- SomeType,
- OtherType,
- }
- struct OurObject {
- contains: ContainedType,
- }
- impl OurObject {
- pub fn get_type(self) -> ContainedType {
- self.contains
- }
- }
- trait MeaninglessNumeric {
- fn numeric(&self) -> i32;
- }
- struct AType {
- value: i32,
- }
- impl fmt::Debug for AType {
- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- write!(f, "AType {}", self.value)
- }
- }
- impl MeaninglessNumeric for AType {
- fn numeric(&self) -> i32 {
- self.value
- }
- }
- struct BType {
- contents: String
- }
- impl fmt::Debug for BType {
- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- write!(f, "BType {}", self.contents)
- }
- }
- impl MeaninglessNumeric for BType {
- fn numeric(&self) -> i32 {
- self.contents.len() as i32
- }
- }
- // These are very contrived examples. In the real world, the values are not
- // created out of thin air but are extracted from data in OurObject.
- fn example1(obj: OurObject) {
- match obj.get_type() {
- ContainedType::SomeType => println!("{:?}", AType { value: 5 }),
- ContainedType::OtherType => println!("{:?}", BType { contents: "hello, world".to_string() }),
- }
- }
- fn example2(obj: OurObject) {
- match obj.get_type() {
- ContainedType::SomeType => println!("{}", AType { value: 5 }.numeric()),
- ContainedType::OtherType => println!("{}", BType { contents: "hello, world".to_string() }.numeric()),
- }
- }
- trait ObjectTrait {
- fn example1(&self);
- fn example2(&self);
- }
- struct Object2<E> {
- thing : E
- }
- impl<E: fmt::Debug + MeaninglessNumeric> ObjectTrait for Object2<E> {
- fn example1(&self){
- println!("{:?}",self.thing);
- }
- fn example2(&self){
- println!("{}",self.thing.numeric());
- }
- }
- fn example3(o : &ObjectTrait){
- o.example1();
- }
- fn example4(o : &ObjectTrait){
- o.example2();
- }
- fn main() {
- let obj1 = OurObject { contains: ContainedType::SomeType };
- let obj2 = OurObject { contains: ContainedType::OtherType };
- let obj3 = Object2 {thing : AType{value:5}};
- let obj4 = Object2 {thing : BType{contents:"Hello, World".to_string()}};
- example1(obj1);
- example2(obj2);
- example3(&obj3);
- example4(&obj4);
- }
Add Comment
Please, Sign In to add comment