簡體   English   中英

在銹中使用特征的泛型函數

[英]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
}

我試圖使add_one為Int泛型,但當我編譯它說類型不匹配

錯誤信息:

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
                             ^

我進一步研究了std :: num :: Int並發現了Int :: one()。

目前適用:

use std::num::Int;

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM