generics and lifetimes

This commit is contained in:
2026-01-22 01:54:12 +00:00
parent b8c7b5e68b
commit c258b53e52
7 changed files with 163 additions and 0 deletions

View File

@@ -0,0 +1,6 @@
[package]
name = "media-aggregator"
version = "0.1.0"
edition = "2024"
[dependencies]

View File

@@ -0,0 +1,60 @@
use ::std::fmt::Display;
use std::fmt::Debug;
pub trait Summary {
fn summarize_author(&self) -> String;
fn summarize(&self) -> String {
// "(Read more...)".to_string()
let x = "a".to_string();
x
}
}
#[derive(Debug)]
pub struct NewsArticle {
pub headline: String,
pub location: String,
pub author: String,
pub content: String,
}
#[derive(Debug)]
pub struct SocialPost {
pub username: String,
pub content: String,
pub reply: bool,
pub repost: bool,
}
impl Summary for NewsArticle {
// fn summarize(&self) -> String {
// format!("{}, by {} ({})", self.headline, self.author, self.location)
// }
fn summarize_author(&self) -> String {
"trad media".to_string() // format!("@{}", self.author)
}
}
// impl Summary for SocialPost {
// fn summarize(&self) -> String {
// format!("{} by {}", self.content, self.summarize_author())
// }
//
// fn summarize_author(&self) -> String {
// format!("@{}", self.username)
// }
// }
// pub fn notify(item: &impl Summary) {
// println!("{}", item.summarize());
// }
pub fn notify<T, U>(item: &T, x: U)
where
T: Summary,
U: Copy + Debug + Display + Clone,
{
println!("{}", item.summarize());
let y = x;
println!("doubled: {:?}", y);
}

View File

@@ -0,0 +1,28 @@
use media_aggregator::{NewsArticle, SocialPost};
use media_aggregator::{Summary, notify};
fn main() {
let article = NewsArticle {
headline: "Chancellor on brink of second bailout for banks".to_string(),
location: "London".to_string(),
author: "The Times".to_string(),
content: "Please subscribe to Premium to read the whole story.".to_string(),
};
let tweet = SocialPost {
content: "running bitcoin".to_string(),
username: "halfin".to_string(),
reply: false,
repost: false,
};
println!("\n --- DEBUG: values ---");
println!("{:?}", article);
// println!("{:?}", tweet);
println!("\n --- DEBUG: article summary ---");
println!("{:?}", article.summarize());
println!("\n --- DEBUG: article notify---");
notify(&article, 5);
}