0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

rustで、参照された変数を更新する

0
Last updated at Posted at 2023-12-28

Rustで、構造体に実装したメソッド内で自身のプロパティを更新する。

例として、以下のように円を表す構造体を考える。

struct Circle {
    radius: f64, // 半径
    area: f64, // 面積
}

円インスタンスを、以下のように半径を与える形で宣言し
この後、半径radiusを元に面積を計算し、circle自身に保持させる事を考える。

    let mut circle = Circle{ radius: 5.0, area: 0.0};

円の半径をr, 面積をSとすると、Sは、円周率πを用いて、

S = πr^2

で導かれる事を使うと、

以下のように、定義するメソッドの仮引数(self)の型に、&mutを付与することで、
書き換え可能な値を参照で渡すことができる。

ただし、以下を用いる
powi
std::f64::consts::PI

use std::f64::consts::PI;

impl Circle {
  // &mut selfによって、可変の参照を渡せる。set_areaは、circleの値を借用している。そのため、set_areaを用いても所有権は移動しない
  fn set_area(&mut self) {
    self.area = PI * self.radius.powi(2)
  }
}

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?