【Rust】Cargoの使い方とcrate(クレート)

### cargoがインストールされていることを確認
$ cargo –version
cargo 1.83.0 (5ffbef321 2024-10-29)

## プロジェクトの作成
$ cargo new hoge

main.rs

use rand::Rng;

fn main() {
    let mut rng = rand::thread_rng();
    for _i in 1..10 {
        println!("{}", rng.gen_range(1, 101));
    }
}

Cargo.tom

[package]
name = "hoge"
version = "0.1.0"
edition = "2021"

[dependencies]
rand = "0.7"

$ cargo run
26
4
61
71
29
17
33
37
59

### C++でライブラリを作る
MathLibrary.h

#pragma once

namespace MathLibrary
{
    class Arithmetic
    {
    public:
        static double Add(double a, double b);

        static double Subtract(double a, double b);

        static double Multiply(double a, double b);

        static double Divide(double a, double b);
    };
}
#include "MathLibrary.h"

namespace MathLibrary
{
    double Arithmetic::Add(double a, double b)
    {
        return a + b;
    }

    double Arithmetic::Subtract(double a, double b)
    {
        return a - b;
    }

    double Arithmetic::Multiply(double a, double b)
    {
        return a * b;
    }

    double Arithmetic::Divide(double a, double b)
    {
        return a / b;
    }


}
#include <iostream>
#include "MathLibrary.h"

int main() {
    double a = 7.4;
    int b = 99;

    std::cout << "a + b = " <<
        MathLibrary::Arithmetic::Add(a, b) << std::endl;
    std::cout << "a - b = " <<
        MathLibrary::Arithmetic::Subtract(a, b) << std::endl;
    std::cout << "a * b = " <<
        MathLibrary::Arithmetic::Multiply(a, b) << std::endl;
    std::cout << "a / b = " <<
        MathLibrary::Arithmetic::Add(a, b) << std::endl;
}

$ g++ -o test MathLibrary.cpp test.cpp && ./test
a + b = 106.4
a – b = -91.6
a * b = 732.6
a / b = 106.4

crateというより、複数ファイルの使用か…