t_wの輪郭

struct

2022/2/18 0:55:00

Rustの構造体


struct User {
    username: String,
    email: String,
    sign_in_count: u64,
    active: bool,
}

fn main() {
    let user1 = User {
        email: String::from("someone@example.com"),
        username: String::from("someusername123"),
        active: true,
        sign_in_count: 1,
    };

    println!("{}", user1.email);    //someone@example.com
}

メソッド記法

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
}