Generic Programming: Conversion


I am struggling a bit with something I think should be easy:

fn drawline<T: Sub<Output = T> + Div<Output = T>> (start: T3<T>, end: T3<T>, n: i64){
// Distance between end and start points
let d   = end - start;
// How many points between limits
let nd  = n as T;
// Construct nd as T3
let ndt = T3::<T>::new(nd,nd,nd);
// Step size between points as T3
let dp  = d / ndt;


Basically what I have is a tuple, "T3" with a type "T", which will most oftenly be either f32 or f64. I want to draw a line between two points of type "T3" and the total number of points is given by "n" which is of type "i64". I need to be able to convert from "i64" to "T", to ensure that the line "let nd = n as T" will work (does not work currently).

Am I approaching this in a wrong way or how would I go about doing it?

A small and easy solution is simply to set "n: T" in the function definition, but I would like to avoid errors by mistype "n = 472.2" points, which would not make sense, since I cannot have "0.2" particle.

Kind regards

Try to use the From trait (or if it has to be converting from a 64 bit integer probably rather TryFrom) for the conversion.

I'm also sceptical of the division operator between T3s that you seem to have, that's not an operator you usually have in math. For your case, implementing Div<T> for T3<T> where T: Div (basically like a scalar times vector multiplication) would be enough anyways and IMO much nicer.

There's also probably some linear algebra crates out there that offer vector / point types and possibly their own mechanisms to help you stay generic over the scalar type. I'm not really knowing much myself about any of those crates.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.