Is it possible to specialize on a static lifetime?

后端 未结 2 1341
我寻月下人不归
我寻月下人不归 2021-01-19 10:49

I want to specialize &\'static str from &\'a str. Something like this:

use std::borrow::Cow;

struct MyString {
    inner:          


        
2条回答
  •  轮回少年
    2021-01-19 11:34

    Rust 1.25.0 does not have specialization of any kind. If I'm reading the specialization RFC correctly, then lifetime specialization will not be supported even when the RFC is implemented:

    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.

    (Emphasis mine)

    There's some examples further in the link that indicate some of the concrete issues.

    I recommend using a Cow to handle the "owned or borrowed" case.

提交回复
热议问题