Hacker News new | past | comments | ask | show | jobs | submit login

Nope in Rust you can only do things with generic types that fit the constraints(called trait bounds in Rust) you've placed on them. So with no constraints you can only do things that every single type supports. In essence it's an implicit vs explicit trade off. C++ implicitly figures out the constraints on generic types whereas Rust requires you to be explicit about them.

Your example in Rust would be

    use std::ops::Mul;
    
    fn double<T: Mul<i32>>(a: T) -> T::Output {
        a * 2
    }
    
    fn main() {
        println!("{}", double(2));
    
        // Can't double &str because it doens't implement Mul<i32>
        // println!("{}", double("Hello"));
    }



https://play.rust-lang.org/?gist=ba8d6368a7fb997586b51580baa...

Also as the GP points out the above fact is crucial for the reasoning around to hold `fn<T>(T) -> T`. An example that breaks those rules is

    fn thing<T: Default>(a: T) -> T {
        T::default()
    }



Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: