简体   繁体   中英

Generic functions using traits in rust

use std::num::Int;

fn main() {
    println!("{}", add_one(4));
}

fn add_one<T: Int>(x: T) -> T {
    return x + 1
}

I'm trying to make add_one generic for Int but when I compile it says types are mismatched

Error message:

src/main.rs:8:16: 8:17 error: mismatched types:
 expected `T`,
    found `_`
(expected type parameter,
    found integral variable) [E0308]
src/main.rs:8     return x + 1
                             ^

I looked into std::num::Int a bit more and found Int::one().

This works for now:

use std::num::Int;

fn main() {
    println!("{}", add_one(4));
}

fn add_one<T: Int>(x: T) -> T {
    return x + Int::one();
}

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