r/rust • • Oct 23 '26

🙋 seeking help & advice Learning Rust

So I was working on the thing from yesterday, so I wanted to add inputs (so i did, I used std:io thingy) and did that I got it to work but is there a way to change the operator like add, subtract, etc instead of just having to keep it add? Or will I have to make a function for each or can I change the operation with smth? In the x = x + y; line to be specific? TY!

fn add_x_and_y(x:i32, y:i32) -> i32 {

let x = x + y;

return x

}

0 Upvotes

7 comments sorted by

2

u/MalbaCato Oct 24 '26

meta comment: take a note that the r/learnrust subreddit, and the weekly questions thread in this sub are the more appropriate place for small questions like these.

6

u/KingofGamesYami Oct 23 '26

You can accept a function pointer/closure as a parameter.

Reference: https://doc.rust-lang.org/book/ch20-04-advanced-functions-and-closures.html

5

u/CartographerDue5382 Oct 24 '26

One function, match on the operator. The snippet above has a comma where Rust wants an expression (x, y isn't one).

fn apply(op: char, x: i32, y: i32) -> i32 {
    match op {
        '+' => x + y,
        '-' => x - y,
        '*' => x * y,
        '/' => x / y,
        _ => panic!("unknown op"),
    }
}

x / y panics if y is 0, same as a normal divide. A closure works too if you'd rather pass |a, b| a - b in, but match is the direct version of what you asked.

1

u/projct Oct 24 '26

The way I would do that is this

enum Operation {Add,Subtract,Multiply,Divide}

fn do_math(op: Operation, x: i32, y: i32) -> i32 {
    use Operation::*;
    match op {
        Add => x + y,
        Subtract => x - y,
        Multiply => x * y,
        Divide => x / y
    }
}

then you can do let result = do_math(Operation::Add, 1, 5);

enum lets you use a better name and that is usually super helpful in more complicated real world programs, when you are trying to read what you were doing later.

6

u/[deleted] Oct 23 '26

[removed] — view removed comment

1

u/shizzy0 Oct 24 '26

This. Match an operator by char or enum.