3

使用共享引用说明Rust所有权概念

 1 year ago
source link: https://www.jdon.com/62801
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

使用共享引用说明Rust所有权概念


共享引用(&T)是复制Copy特性(见这里,值复制)。
下面是一个常用类型的例子,字符串slice片&str。
下面我们可以在第3行和第4行将name传递给do_something。注意,我们正在复制引用。

fn main() {
    let name: &'static str = "Rust";
    do_something(name);
    do_something(name);
}

fn do_something(name: &str) {
    println!("Hello, {:?}!", name);
}

输出:

Hello, Rust!
Hello, Rust!

下面代码在把name传给do_something之前调用.clone()是多余的。

fn main() {
    let name: &'static str = "Rust";
    do_something(name.clone());
    do_something(name.clone());
}

fn do_something(name: &str) {
    println!("Hello, {:?}!", name);
}

根据Clippy的建议,<&str>::clone(&name)这个习惯语会克隆引用。该程序可以编译,但我不确定这是否是习惯用法。

fn main() {
    let name: &'static str = "Rust";
    do_something(<&str>::clone(&name));
    do_something(<&str>::clone(&name));
}

fn do_something(name: &str) {
    println!("Hello, {:?}!", name);
}

 


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK