impl
2022/2/18 1:16:00
fn test(closure: impl 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#複数のトレイト境界を構文で指定する
fn returns_summarizable() -> impl Summary {
Tweet {
username: String::from("horse_ebooks"),
content: String::from(
"of course, as you probably already know, people",
),
reply: false,
retweet: false,
}
}
https://doc.rust-jp.rs/book-ja/ch10-02-traits.html#トレイトを実装している型を返す
pub fn notify(item: &impl Summary) {
println!("Breaking news! {}", item.summarize());
}
https://doc.rust-jp.rs/book-ja/ch10-02-traits.html#引数としてのトレイト
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 {}
fn main() {
let news_article = NewsArticle{
headline: String::from("Headline"),
location: String::from("somewhere"),
author: String::from("somebody"),
content: String::from("something")
};
println!("{}", news_article.summarize());
}
https://doc.rust-jp.rs/book-ja/ch10-02-traits.html#デフォルト実装
trait Summary {
fn summarize(&self) -> String;
}
struct NewsArticle {
pub headline: String,
pub location: String,
pub author: String,
pub content: String,
}
impl Summary for NewsArticle {
fn summarize(&self) -> String {
format!("{}, by {} ({})", self.headline, self.author, self.location)
}
}
fn main() {
let news_article = NewsArticle{
headline: String::from("Headline"),
location: String::from("somewhere"),
author: String::from("somebody"),
content: String::from("something")
};
println!("{}", news_article.summarize());
}
https://doc.rust-jp.rs/book-ja/ch10-02-traits.html#トレイトを型に実装する
impl
ブロック内のself
を引数に取らない関数。
Javaのstaticメソッドっぽさがある。
struct Rectangle {width:f64, height:f64}
impl Rectangle {
fn square(size: f64) -> Rectangle { //関連関数
Rectangle { width: size, height: size }
}
}
fn main() {
let rect = Rectangle::square(32.);
println!("width: {}, height: {}", rect.width, rect.height); //width: 32, height: 32
}
struct Body {
weight: f64,
height: f64,
}
impl Body {
fn bmi_calc(&self) -> f64 {
self.weight/(self.height*self.height)
}
}
fn main() {
let body = Body{weight: 60., height: 1.7};
let bmi = body.bmi_calc();
println!("bmi: {}", bmi); //20.761245674740486
}