【Rust】関数

fn add(x: i32, y: i32) -> i32 {
    return x + y;
}

fn main(){
    let r = add(4, 7);
    println!("{}", r);
}

C++で関数を使って書いてみる

#include <iostream>
#include <stdio.h>
#include <string>
#include <map>

int total(std::map<std::string, int> &cart){
    int price = 0;
    for(auto i : cart){
        price = price + i.second;
    }
    std::cout << "※合計: " << price << "円" << std::endl;
    return price;
}

int tax(int price) {
    int tax_price = price * 0.1;
    std::cout << "※税: " << tax_price << "円" << std::endl;
    return tax_price;
}

void cashier(std::map<std::string, int> &cart) {
    for(auto i: cart) {
        std::cout << i.first << ": " << i.second << "円" << std::endl;
    }

    int price = total(cart);
    int tax_price = tax(price);
    
    std::cout << "お会計: " << price + tax_price << "円" << std::endl;
}

int main()
{
    std::map<std::string, int> cart;

    cart["Crab mayoo"] = 2280;
    cart["Salad"] = 780;
    cart["Cola"] = 190;

    cashier(cart);
    
    return 0;
}

上記をRustで記述する。

use std::collections::HashMap;

fn total(cart :HashMap<&str, u32> )-> u32 {
    let mut price: u32 = 0;
    for (key, value) in cart.iter() {
        price = price + value;
        println!("{} : {}円", key, value);
    }
    println!("※合計 {}円", price);
    return price;
}

fn tax(price: u32) -> u32 {
    let tax: u32 = price / 10;
    println!("※税 {}円", tax);
    return tax;
}

fn cashier(cart :HashMap<&str, u32>) {
    let price: u32 = total(cart);
    let tax_price = tax(price);
    println!("合計 {}円", price + tax_price);
}

fn main(){
    let mut cart = HashMap::new();
    cart.insert("Crab mayoo", 2280);
    cart.insert("Salad", 780);
    cart.insert("Cola", 190);

    cashier(cart);
}

なるほど、u32 * floatはできないので、price * 0.1とするとエラーになる。
Rustは型指定が結構大変だなぁ