rust - 是否可以专注于静态生命周期?

标签 rust traits lifetime specialization

我想专攻&'static str来自 &'a str :

use std::borrow::Cow;

struct MyString {
    inner: Cow<'static, str>,
}

impl From<&'static str> for MyString {
    fn from(x: &'static str) -> Self {
        MyString {
            inner: Cow::Borrowed(x),
        }
    }
}

impl<T: Into<String>> From<T> for MyString {
    fn from(x: T) -> Self {
        MyString {
            inner: Cow::Owned(x.into()),
        }
    }
}

fn main() {
    match MyString::from("foo").inner {
        Cow::Borrowed(..) => (),
        _ => {
            panic!();
        }
    }

    let s = String::from("bar");
    match MyString::from(s.as_ref()).inner {
        Cow::Owned(..) => (),
        _ => {
            panic!();
        }
    }

    match MyString::from(String::from("qux")).inner {
        Cow::Owned(..) => (),
        _ => {
            panic!();
        }
    }
}

要点是 MyString将静态分配的字符串文字存储为 &'static str和所有其他字符串作为 String .这允许 MyString避免使用生命周期参数——即 MyString<'a> ,这对我的 API 至关重要,同时允许调用者传入任何类型的字符串并拥有 MyString自动做正确的事情。

问题是代码无法编译:

error[E0119]: conflicting implementations of trait `std::convert::From<&'static str>` for type `MyString`:
  --> src/main.rs:15:1
   |
7  | impl From<&'static str> for MyString {
   | ------------------------------------ first implementation here
...
15 | impl<T: Into<String>> From<T> for MyString {
   | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ conflicting implementation for `MyString`

有什么技巧可以让我做我想做的事吗?如果不是,那么 Rust 会永远支持终生特化吗?

最佳答案

Rust 1.51.0 没有任何类型的专门化。如果我正在阅读 the specialization RFC正确,那么即使实现了 RFC,生命周期特化也将被支持:

A hard constraint in the design of the trait system is that dispatch cannot depend on lifetime information. In particular, we both cannot, and should not allow specialization based on lifetimes:

  • We can't, because when the compiler goes to actually generate code ("trans"), lifetime information has been erased -- so we'd have no idea what specializations would soundly apply.

  • We shouldn't, because lifetime inference is subtle and would often lead to counterintuitive results. For example, you could easily fail to get 'static even if it applies, because inference is choosing the smallest lifetime that matches the other constraints.

(强调我的)

链接中还有一些示例说明了一些具体问题。

我建议使用 Cow 来处理“拥有或借用”的情况。

关于rust - 是否可以专注于静态生命周期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37053567/

相关文章:

c++ - 来自 QVariantList 的 std::function 的通用调用

php - 我可以在特征中使用父类的属性吗?

Rust:错误 [E0495]:由于需求冲突,无法推断出 autoref 的适当生命周期

rust - 为什么闭包的可变引用参数不会比函数调用更长久?

rust - Vanilla Rust中的目录遍历

rust - 使用 HMAC 作为泛型

scala - 如何使用 None 类型约束专门化一个特征?

rust - 如何在处理生命周期和借用规则的同时将Rust ZipArchive和ZipFile放入单个读取实现结构中

loops - 尝试在循环中更新 Option<&str> 时获取 "temporary value dropped while borrowed"

rust - 有没有一种方法可以基于常量的存在进行条件编译?