0

In my process of learning Rust I have come across a problem that I don't know how to solve elegantly. I want to do operations on Image::Rgb data, but I get the error that they are not implemented. For example:

let rgb = Rgb([40u8, 40, 40]);
let val: u8 = 60;
val*rgb;

Results in the trait Mul<Rgb<u8>> is not implemented for u8. Of course I can do:

rgb.map(|x| x * val);

But that results in a mess if there are more operations/several rgb colors. Is there any workaround here? How can I implement that Mul trait?

Edit for reference: I have three points (v1, v2, v3) and a color per point. I want to interpolate the color in between the points, just like here (the color_p formula). Then not only do I have to do three multiplications but also summing and division. I think map too complicated in that case.

javirk
  • 23
  • 5
  • Import the trait and implement the required method, just like any other trait :) https://doc.rust-lang.org/std/ops/trait.Mul.html – isaactfa Aug 13 '22 at 19:09
  • 3
    @isaactfa [I don't think it will be possible here](https://stackoverflow.com/a/25415289/11527076). `Rgb` is from the `image` crate and `Mul` is from `std`. – prog-fh Aug 13 '22 at 19:40
  • Can you give an example of why the `map` approach is undesired? That's the correct way to do this operation. – cdhowie Aug 13 '22 at 19:46
  • @cdhowie I have three points (v1, v2, v3) and a color per point. I want to interpolate the color in between the points, just like here: https://codeplea.com/triangular-interpolation (the color_p formula). Then not only do I have to do three multiplications but also summing and division. Isn't `map` very difficult in that case? – javirk Aug 13 '22 at 20:11
  • Destructure the rgb struct `let [r, g, b] = rgb.0` and work on your color values as you would in other languages – MeetTitan Aug 13 '22 at 20:20
  • @javirk There's multiple ways that can be addressed. However, `map` is the _exact_ answer to the question you have actually posed ("how to multiply Rgb and u8"). If you want a different answer then you probably need to ask a different question. – cdhowie Aug 13 '22 at 20:22
  • @cdhowie You are totally right, my mistake. I changed the title to better suit my question. MeetTitan: If that's the only option, I will do it that way, thanks! – javirk Aug 13 '22 at 20:39
  • @prog-fh Oh that's my bad, I didn't realize `Rgb` was from a crate. – isaactfa Aug 13 '22 at 23:47

0 Answers0