首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在Rust中,clone()和to_owned()有什么不同?

在Rust中,clone()和to_owned()有什么不同?
EN

Stack Overflow用户
提问于 2014-03-08 11:09:52
回答 1查看 26.9K关注 0票数 77

在Rust中,Clone是指定clone方法(和clone_from)的特征。一些性状,如StrSliceCloneableVector,指定了to_owned fn。为什么一个实现需要这两者?有什么关系?

我用Rust字符串做了一个实验,它有两种方法,它证明了这是有区别的,但我不理解它:

代码语言:javascript
复制
fn main() {
    test_clone();
    test_to_owned();
}

// compiles and runs fine    
fn test_clone() {
    let s1: &'static str = "I am static";
    let s2 = "I am boxed and owned".to_string();

    let c1 = s1.clone();
    let c2 = s2.clone();

    println!("{:?}", c1);
    println!("{:?}", c2);

    println!("{:?}", c1 == s1);  // prints true
    println!("{:?}", c2 == s2);  // prints true
}

fn test_to_owned() {
    let s1: &'static str = "I am static";
    let s2 = "I am boxed and owned".to_string();

    let c1 = s1.to_owned();
    let c2 = s2.to_owned();

    println!("{:?}", c1);
    println!("{:?}", c2);

    println!("{:?}", c1 == s1);   // compile-time error here (see below)
    println!("{:?}", c2 == s2);
}

to_owned示例的编译时错误为:

代码语言:javascript
复制
error: mismatched types: expected `~str` but found `&'static str` 
(str storage differs: expected `~` but found `&'static `)
clone.rs:30     println!("{:?}", c1 == s1);

为什么第一个例子可以工作,而第二个不行?

EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22264502

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档