fn
2022/2/16 23:25:00
Rustの関数
Rustの関数
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#トレイトを型に実装する
pub trait Summary {
fn summarize(&self) -> String;
}
https://doc.rust-jp.rs/book-ja/ch10-02-traits.html#トレイトを定義する
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
}