简体   繁体   中英

How can I simplify multiple uses of BigInt::from()?

I wrote a program where I manipulated a lot of BigInt and BigUint values and perform some arithmetic operations.

I produced code where I frequently used BigInt::from(Xu8) because it is not possible to directly add numbers from different types (if I understand correctly).

I want to reduce the number of BigInt::from in my code. I thought about a function to "wrap" this, but I would need a function for each type I want to convert into BigInt / BigUint :

fn short_name(n: X) -> BigInt {
    return BigInt::from(n)
}

Where X will be each type I want to convert.

I couldn't find any solution that is not in contradiction with the static typing philosophy of Rust.

I feel that I am missing something about traits, but I am not very comfortable with them, and I did not find a solution using them.

Am I trying to do something impossible in Rust? Am I missing an obvious solution?

To answer this part:

I produced code where I frequently used BigInt::from(Xu8) because it is not possible to directly add numbers from different types (if I understand correctly).

On the contrary, if you look at BigInt 's documentation you'll see many impl Add :

impl<'a> Add<BigInt> for &'a u64
impl Add<u8> for BigInt

and so on. The first allows calling a_ref_to_u64 + a_bigint , the second a_bigint + an_u8 (and both set OutputType to be BigInt ). You don't need to convert these types to BigInt before adding them! And if you want your method to handle any such type you just need an Add bound similar to the From bound in Frxstrem's answer . Of course if you want many such operations, From may end up more readable.

The From<T> trait (and the complementary Into<T> trait) is what is typically used to convert between types in Rust. In fact, the BigInt::from method comes from the From trait.

You can modify your short_name function into a generic function with a where clause to accept all types that BigInt can be converted from:

fn short_name<T>(n: T) -> BigInt // function with generic type T
where
    BigInt: From<T>, // where BigInt implements the From<T> trait
{
    BigInt::from(n)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM