之前通过学习了解到,rust的对象传递到函数或对象赋值给另一个对象之后对象会被移除,如果我们要让原有对象依然存在,就需要使用引用(或借用)具体的操作方法已在下午代码注释写明
//引用
fn main() {
//之前提到,这种情况 a在调用函数之后空间将会释放没有办法再使用
let a:String=String::from("hello");
fun_demo01(a);
//如果我们想要函数调用之后还能使用,需要使用引用
let b:String=String::from("hello");
//引用的传参形式
fun_quote(&b);
println!("b={}", b);
//因为引用时没办法直接修改对象的,如果我们想修改我们传入的对象要怎么做呢?
//这个时候我们就要用到--借用
let mut c:String=String::from("hello");
let c1=&mut c;
fun_borrow(c1);
//在rust2018 中这种情况说会报错的
println!("c_y={}", c1);
}
fn fun_demo01(a:String) {
}
//这就是引用的函数申明格式
fn fun_quote(b:&String){
//这里会报错,因为rust的引用是没有对象空间的修改权的只有使用权力
//b.push("world");
println!("{}", b);
}
//以下时借用函数的声明格式
fn fun_borrow(c:&mut String){
c.push_str("world");
println!("c={}", c);
}