是否可以专门研究静态生命周期?

2024-04-04

我想专攻&'static str from &'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 没有任何类型的专门化。如果我在读书专业化 RFC https://github.com/rust-lang/rfcs/blob/master/text/1210-impl-specialization.md#interaction-with-lifetimes正确的话,那么终身专业化将not即使实现了 RFC,也能得到支持:

特质系统设计中的一个硬约束是调度 不能依赖于生命周期信息。尤其,我们都不能, 并且不应允许基于生命周期的专业化:

  • 我们不能,因为当编译器实际生成代码(“trans”)时,生命周期信息已被删除 - 所以我们没有 知道哪些专业最适合。

  • 我们不应该这样做,因为生命周期推断是微妙的,并且常常会导致违反直觉的结果。例如,你很容易失败 要得到'static即使它适用,因为推理正在选择 与其他约束相匹配的最小寿命。

(强调我的)

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

我建议使用Cow处理“自有或借用”案件。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

是否可以专门研究静态生命周期? 的相关文章

随机推荐