gpt4 book ai didi

rust - 具有可变借用的函数的返回类型有什么影响?

转载 作者:行者123 更新时间:2023-11-29 08:00:16 24 4
gpt4 key购买 nike

<分区>

以下 Rust 代码构建并运行:

fn func(s: &mut String) -> i32 {
s.push_str("!");
println!("{}", s);
1
}

fn main() {
let mut x = String::from("hello world");
let v = func(&mut x);
println!("{}", v);
let r = &x[..];
println!("{}", r);
}

如果func的返回类型改为&str,我得到

error[E0502]: cannot borrow `x` as immutable because it is also borrowed as mutable
--> src/main.rs:11:18
|
9 | let v = func(&mut x);
| - mutable borrow occurs here
10 | println!("{}", v);
11 | let r = &x[..];
| ^ immutable borrow occurs here
12 | println!("{}", r);
13 | }
| - mutable borrow ends here

我知道在给定范围内,只允许一个可变引用,但返回类型有什么关系呢?

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com