[][src]Function tao_of_rust::ch03::generics::foo

pub fn foo<T>(x: T) -> T

泛型

Base usage: 自定义泛型函数

fn foo<T>(x: T) -> T {
   return x;
}

assert_eq!(foo(1), 1);
assert_eq!(foo("hello"), "hello");Run

Base usage: 自定义泛型结构体

struct Point<T> {  x: T, y: T }Run

Base usage: foo<T>静态分发等价于下面代码

fn foo_1(x: i32) -> i32 {
    return x;
}
fn foo_2(x: &'static str) -> &'static str {
    return x;
}
foo_1(1);
foo_2("2");Run