LoginSignup
5
5

More than 5 years have passed since last update.

RustでC++のiostreamみたいなものを作ってHello worldしてみた

Posted at

初投稿です。

稚拙ながら、Rustで演算子オーバーロードの習作としてC++のiostreamを模倣してみました。
iostreamをRustに移植するのが目的ではないので、標準出力のみの実装となっています。

helloworld.rs
use std::ops::Shl;

struct Rsout;
struct Endl;

impl<'a> Shl<&'a str> for Rsout {
    type Output = Rsout;

    fn shl(self, _rhs: &'a str) -> Rsout {
        print!("{}", _rhs);
        self
    }
}

impl Shl<i32> for Rsout {
    type Output = Rsout;

    fn shl(self, _rhs: i32) -> Rsout {
        print!("{}", _rhs);
        self
    }
}

impl Shl<Endl> for Rsout {
    type Output = Rsout;

    fn shl(self, _rhs: Endl) -> Rsout {
        print!("\n");
        self
    }
}


fn main() {
    Rsout << "Hello, " << "world!" << Endl;
    Rsout << "1 + 2 = " << 1 + 2 << Endl;
}

ちなみにC++で書いた同じプログラムがこちら。

helloworld.cpp
#include <iostream>

using namespace std;

int main()
{
    cout << "Hello, " << "world!" << endl;
    cout << "1 + 2 = " << 1 + 2 << endl;
}

まだライフタイムの部分の書き方がよく分かっていないため、&str型の実装に時間をかけてしまいました……。
概念は理解出来ていると思うのですが、やはり量を書かないと慣れませんね。

Rustでの演算子オーバーロードのやり方については以下を参考にしました。
The book - Operators and Overloading
ライフタイムについては以下を参考にしました。
The book - Lifetimes

5
5
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
5
5