インプリメンテーションとは構造体にメソッドを追加するもの。Rustにクラスはない。
struct Rect { width: u32, height: u32}
impl Rect {
fn area(&self) -> u32 {
self.width * self.height
}
}
fn main(){
let r = Rect {width: 200, height: 300};
println!("{}", r.area());
}
C++のclass
#include <iostream>
#include <string>
class Car {
public:
std::string owner;
std::string color;
int number;
};
auto main(void) -> int {
auto a = Car();
a.owner = "山田";
a.color = "blue";
a.number = 1234;
std::cout << "a.owner =" << a.owner << ", a.color =" << a.color
<< ", a.number =" << a.number << std::endl;
}
rustでimplを使ってclassを書く
struct Car {
owner: String,
color: String,
number: u32,
}
impl Car {
fn prnt(&self) {
println!("{} {} {}", self.owner, self.color, self.number);
}
}
fn main(){
let c = Car {owner: "山田".to_string(), color: "blue".to_string(), number: 1234};
c.prnt();
}
$ ./main
山田 blue 1234
なるほど〜