Plottersという描画ライブラリがあるらしい。第2章 2.2.1で描いていたヒストグラムが描きたいので使ってみることにした。

plotters - Rust

例としてHistogramを描くものもあったのでとりあえずサンプルコードを覗いてみる。

38/plotters

とりあえず、サンプルコードを写経してcargo runしてみたら次のようなエラーが出た

error[E0277]: the trait bound `{float}: SizeDesc` is not satisfied
  --> src/main.rs:14:36
   |
14 |         .caption("Histogram Test", ("sans-serif", 50.0))
   |                                    ^^^^^^^^^^^^^^^^^^^^ the trait `SizeDesc` is not implemented for `{float}`
   |
   = help: the following implementations were found:
             <RelativeSize as SizeDesc>
             <i32 as SizeDesc>
             <style::size::RelativeSizeWithBound as SizeDesc>
             <u32 as SizeDesc>
   = note: required because of the requirements on the impl of `IntoTextStyle<'_>` for `(&str, {float})`

error: aborting due to previous error

For more information about this error, try `rustc --explain E0277`.
error: could not compile `histogram`

trait SizeDescがfloatむけに実装されていないよ?とのことだがこっちはまずtraitがなんなのかよくわからんのじゃ

とりあえず、このエラーに関しては50.050に変えたら動いた。サンプルコード間違ってんぞって思ったがこっちの環境設定が悪い可能性も微レ存なのでissueは送っていない

動いたはいいが、traitとは?という感じだったので調べてみた

Rust By Example 日本語版

継承みたいな概念に見えるが違うのかな?いまいちよくわからん・・・とりあえず上のエラーで出ているSizeDescというtraitの実装をみてみた

pub trait SizeDesc {
    /// Convert the size into the number of pixels
    ///
    /// - `parent`: The reference to the parent container of this size
    /// - **returns**: The number of pixels
    fn in_pixels<T: HasDimension>(&self, parent: &T) -> i32;
}

impl SizeDesc for i32 {
    fn in_pixels<D: HasDimension>(&self, _parent: &D) -> i32 {
        *self
    }
}

impl SizeDesc for u32 {
    fn in_pixels<D: HasDimension>(&self, _parent: &D) -> i32 {
        *self as i32
    }
}

よくわからないけど組み込み型のi32u32にメソッドを足せるの?すごくない?とりあえず上のエラーの意味するところはわかった気がする

impl SizeDesc for float {
	...
}

みたいな実装はされていないよ?っていうことですね。しかし、なぜこのエラーが出たのか微妙に解せないので今度は.captionメソッドを追ってみる。.captionplotters::prelude::ChartBuilderのメソッドなのでドキュメントを見てみる。