目次

Rustの勉強[高度なトレイト その4]

ぎじゅつ

始めに

#

NO IMAGE高度なトレイト - The Rust Programming Language 日本語版

を読んでいる

お勉強

#

NO IMAGE高度なトレイト - The Rust Programming Language 日本語版

ここかららしい

メモ

#
use std::fmt;

trait OutlinePrint: fmt::Display {
    fn outline_print(&self) {
        let output = self.to_string();
        let len = output.len();
        println!("{}", "_".repeat(len + 4));
        println!("_{}_", " ".repeat(len + 2));
        println!("_ {} _", output);
        println!("_{}_", " ".repeat(len + 2));
        println!("{}", "_".repeat(len + 4));
    }
}
  • これ何の話してんだって思ったけどstdライブラリか
error[E0277]: the trait bound `Point: std::fmt::Display` is not satisfied
  --> src/main.rs:20:6
   |
20 | impl OutlinePrint for Point {}
   |      ^^^^^^^^^^^^ `Point` cannot be formatted with the default formatter;
try using `:?` instead if you are using a format string
   |
   = help: the trait `std::fmt::Display` is not implemented for `Point`
  • ディスプレイの実装を満たしたらしい
  • あー

時として、あるトレイトに別のトレイトの機能を使用させる必要がある可能性があります。この場合、依存するトレイトも実装されることを信用する必要があります。信用するトレイトは、実装しているトレイトのスーパートレイトです。

  • ここの依存関係のトレイトも満たしてねッて感じだった

ニュータイプという用語は、 Haskellプログラミング言語に端を発しています。

  • ここかっこよくて抜選した

このパターンを使用するのに実行時のパフォーマンスを犠牲にすることはなく、ラッパ型はコンパイル時に省かれます

  • なんか凄そうなこと書いてあるぞ

  • ニュータイプパターン、まったくわからん

  • あーなるほど

use std::fmt;

struct Wrapper(Vec<String>);

impl fmt::Display for Wrapper {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "[{}]", self.0.join(", "))
    }
}

fn main() {
    let w = Wrapper(vec![String::from("hello"), String::from("world")]);
    println!("w = {}", w);
}
  • そもそも前提として同じプロジェクト内か同じクレート内じゃないと実装できない制約をwrapperで囲んでいるという話

まとめ

#
  • まぁエッジケースだな(2回目)
  • 普通はエラーがでて初めて調べることになりそう

次は高度な型

NO IMAGE高度な型 - The Rust Programming Language 日本語版