首页 > 解决方案 > 应该首选将字符串文字转换为字符串

问题描述

在 Rust 中,有几种方法可以从字符串文字创建字符串:

fn main() {
    let s_from = String::from("string"); // type on the right of the operator
    let s_into: String = "string".into(); // type on the left of the operator
    let s_to_string = "string".to_string(); // expresses type
    let s_to_owned = "string".to_owned(); // expresses ownership
    assert_eq!(s_from, s_into);
    assert_eq!(s_from, s_to_string);
    assert_eq!(s_from, s_to_owned);
}
  1. 是否有规则遵循与操作员相关的阅读方向?
  2. 有理由支持From/Into胜过to_string()/to_owned()吗?
  3. 是否有理由偏爱其中一个而不是其他所有?

随着几个开发人员在一个项目上工作,会发生这些混合使用。

标签: rust

解决方案


推荐阅读