where
2022/2/21 1:00:00
fn test<T>(closure:T) where T: Fn(u32) -> u32 {
assert_eq!(closure(10), 11);
}
let closure = |x| {
x+1
};
test(closure);
pub fn notify(item: &(impl Summary + Display)) {
pub fn notify<T: Summary + Display>(item: &T) {
pub fn notify<T>(item: &T) where T:Summary + Display {
→pub fn notify<T>(item: &T) where T:Summary + Display {
https://doc.rust-jp.rs/book-ja/ch10-02-traits.html#複数のトレイト境界を構文で指定する
use std::fmt;
trait Summary {
fn summarize(&self) -> String {
String::from("(Read more...)")
}
}
struct NewsArticle {
pub headline: String,
pub location: String,
pub author: String,
pub content: String,
}
impl Summary for NewsArticle {}
impl fmt::Display for NewsArticle {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
write!(f, "({}, {}, {}, {})", self.headline, self.location, self.author, self.content)
}
}
fn notify<T>(item:T) where T:Summary + fmt::Display {
println!("Breaking news! {}", item.summarize());
}
fn main() {
let news_article = NewsArticle{
headline: String::from("Headline"),
location: String::from("somewhere"),
author: String::from("somebody"),
content: String::from("something")
};
notify(news_article);
}