在Rust中,我经常编写如下代码:
transform
函数如下。我有一些不变的输入,并返回一个新分配的输出:
// the transform function doesn't modify inp. instead, it returns something new.
fn transform(inp: String) -> String { // with reference: inp: &String
let buf: Vec<_> = inp.as_bytes().iter().map(|x| x + 1).collect();
String::from_utf8_lossy(&buf).to_string()
}
// using the transform function
fn main() {
let msg: String = String::from("HAL9000");
println!("{}", msg);
println!("{}", transform(msg)); // with reference: &msg
}
如果我不使用参考资料,会影响性能吗
inp
参数设置为
使改变
作用或者编译器是否认识到了这一点
inp
,因为它是不可变的,可以重用/引用吗?换句话说,是否值得额外的努力来声明不可变的输入参数作为引用,比如C++,以避免复制巨大的数据结构?