Borrowing
fn main() {
let s1 = String::from("hello");
let len = calculate_len(&s1);
println!("the len of {} is {}", s1, len);
}
fn calculate_len(s: &String) -> usize {
s.len()
}
&操作是引用,*操作是解引用。
在calculate_len函数中,s是一个字符串引用。构建引用的动作叫做借用。引用默认都是不可变的,不能通过一个不可变引用去修改变量的值。
Mutable References
可变引用,当变量和引用都用mut修饰时,变量是可变的,引用也是可变的。这时,可以通过可变引用修改变量的值。
fn main() {
let mut s = String::from("hello");
change_string(&mut s);
println!("s: {}", s);
}
fn change_string(s: &mut String) {
s.push_str(" world!");
}
error[E0499]: cannot borrow s as mutable more than once at a time
任何一个作用域内,只允许有一个可变引用存在。
fn main() {
let mut s = String::from("hello");
let s1 = &mut s;

本文介绍了Rust编程语言中字符串引用的不可变与可变特性,展示了如何创建和使用它们,以及在作用域和生命周期管理中的注意事项,特别强调了野指针(danglingreferences)的概念和错误处理。
最低0.47元/天 解锁文章
259

被折叠的 条评论
为什么被折叠?



