t_wの輪郭

Feedlyでフォローするボタン
Rust関数

fn

2022/2/16 23:25:00

Rustの関数

引数の型として特質を使う引数の型が複数の特質を実装していることを指定する戻り値の型が特質を実装していることを指定する特質のデフォルト実装特質を型に実装する特質を定義するメソッド記法
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#トレイトを型に実装する

メソッド記法

2022/2/18 1:27:00
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
}