Last active: 2 years ago
Box lifetime bounds for dyn trait
use crate::post::{Post, Summary, Tweet, Weibo};
mod post;
fn create_one<'a>(
switch: bool,
username: &'a str,
title: String,
content: String,
) -> Box<dyn Summary + 'a> {
let post = Post::new(title, username, content);
if switch {
Box::new(Weibo::new(username, post))
} else {
Box::new(Tweet::new(username, post))
}
}
fn main() {
let username = "xfy";
let test = create_one(
true,
username,
String::from("test"),
String::from("Hello world"),
);
println!("{}", test.summarize())
}
pub struct Weibo<'a> {
username: &'a str,
post: Post<'a>,
}
impl<'a> Weibo<'a> {
pub fn new(username: &'a str, post: Post<'a>) -> Self {
Self { username, post }
}
}
pub struct Tweet<'a> {
username: &'a str,
post: Post<'a>,
}
impl<'a> Tweet<'a> {
pub fn new(username: &'a str, post: Post<'a>) -> Self {
Self { username, post }
}
}
pub struct Post<'a> {
title: String,
author: &'a str,
content: String,
}
impl<'a> Post<'a> {
pub fn new(title: String, author: &'a str, content: String) -> Self {
Self {
title,
author,
content,
}
}
}
pub trait Summary {
fn summarize(&self) -> String;
}
impl<'a> Summary for Weibo<'a> {
fn summarize(&self) -> String {
format!("Post {}, author is {}", self.post.title, self.username)
}
}
impl<'a> Summary for Tweet<'a> {
fn summarize(&self) -> String {
format!("Post {}, author is {}", self.post.title, self.username)
}
}