【发布时间】:2020-03-29 07:10:22
【问题描述】:
我对 Rust 很陌生,所以这很可能是一个愚蠢的问题。
我有几个问题。
我有这两个功能:
fn modifier2(mut ptr: Box<String>) -> Box<String> {
println!("In modifier2...");
println!("Ptr points to {:p}, and value is {}", ptr, *ptr);
*ptr = ptr.to_uppercase();
println!("Exit modifier2...");
ptr
}
fn modifier3(ptr: &mut Box<String>) {
println!("In modifier3...");
println!("Ptr points to {:p}, and value is {}", ptr, *ptr);
println!("Ptr points to {:p}, and value is {}", *ptr, **ptr);
**ptr = "another".to_uppercase();
//**ptr = **ptr.to_uppercase(); //error[E0614]: type `str` cannot be dereferenced
println!("Exit modifier3...");
}
我这样称呼他们:
let mut answer = Box::new("Hello World".to_string());
answer = modifier2(answer);
println!("called modifier2(): {} length: {}", answer, answer.len());
let mut answer = Box::new("Hello World".to_string());
modifier3(&mut answer);
println!("called modifier3(): {} length: {}", answer, answer.len());
结果如下,我觉得很好:
In modifier2...
Ptr points to 0x2145fa1d990, and value is Hello World
Exit modifier2...
called modifier2(): HELLO WORLD length: 11
In modifier3...
Ptr points to 0x50426ffb60, and value is Hello World
Ptr points to 0x2145fa1dc50, and value is Hello World
Exit modifier3...
called modifier3(): ANOTHER length: 7
我有两个问题:
1) 在 fn modifier2(mut ptr: Box) -> Box 中,将ptr设为静音有什么意义?它与 fn modifier2(ptr: mut Box) -> Box 有何不同?
2) 在 fn modifier3 的注释行中,即 **ptr = **ptr.to_uppercase();,导致错误“error[E0614]: type str cannot be dereferenced”,而我可以在 fn 修饰符2 中做同样的大写()?
感谢您的帮助。
编辑: 如果我像这样更改modifier3():
fn modifier3(&mut ptr: &mut Box<String>) {
println!("In modifier3...");
println!("Ptr points to {:p}, and *PTR points to {}, and value is {}", ptr, *ptr, **ptr);
*ptr = "another".to_uppercase(); //or **ptr = *"another".to_uppercase();
println!("Exit modifier3...");
}
它给出了以下错误:
error[E0277]: the size for values of type `str` cannot be known at compilation time
--> src\main.rs:99:5
|
99 | println!("Ptr points to {:p}, and *PTR points to {}, and value is {}", ptr, *ptr, **ptr);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time
这里对 &mut ptr 的用法有点困惑。
谢谢。
【问题讨论】:
标签: rust rust-cargo