如何指定一个"通用参考号";Rust中的类似物?确切地说,我想写一些类似于以下C++的东西:
template<typename T>
void func(T&& t) {
otherfunc(std::forward(t));
}
在Rust中我该怎么做?
例如,如果值作为引用或移动值传递,我不想键入两次相同的代码来覆盖两种不同的情况,例如,我想写一个容器,并且必须有一个add
方法。
我应该如何写它来涵盖这两种情况,而不是对引用和移动值的情况进行复制粘贴?
完全可以编写同时接受引用和拥有值的函数。当存在泛型参数T
时,可以使用引用类型(如&str
(对其进行实例化。
例如,这是有效的:
use std::ops::Add;
fn add<T: Add>(lhs: T, rhs: T) -> T::Output {
lhs + rhs
}
fn main() {
assert_eq!(add(5, 37), add(&5, &37));
}
这是因为i32
和&i32
都实现了Add
特性。
函数参数中经常使用的特性有:
AsRef<T>
Into<T>
例如:
fn foo(arg: impl AsRef<str>) {
let _: &str = arg.as_ref();
}
fn bar(arg: impl Into<Box<i32>>) {
let _: Box<i32> = arg.into();
}
fn main() {
foo("hello");
foo(String::from("world"));
foo(&String::from("!"));
bar(42);
bar(Box::new(42));
}