【Rust 学习笔记】References and Borrowing

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

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;
  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值