[−][src]Function tao_of_rust::ch06::functions::generic_function
pub fn generic_function()
函数:泛型函数
Base usage: 泛型函数可推断类型
use std::ops::Mul; fn square<T: Mul<T, Output=T>>(x: T, y: T) -> T { x * y } fn main() { let a: i32 = square(37, 41); let b: f64 = square(37.2, 41.1); assert_eq!(a, 1517); assert_eq!(b, 1528.92); // 浮点数可能执行结果有所差别 }Run
Base usage: 使用turbofish操作符
use std::ops::Mul; fn square<T: Mul<T, Output = T>>(x: T, y: T) -> T { x * y } fn main() { let a = square::<u32>(37, 41); let b = square::<f32>(37.2, 41.1); assert_eq!(a, 1517); assert_eq!(b, 1528.9199); }Run