简体   繁体   中英

Can `impl From<ZST> for &'static str` (static impl) replace `impl<'a> From<ZST> for &'a str` (generic impl)?

Given the following condition:

/// Zero Sized Type
struct ZST;

/// What the ZST converts into
const TEXT: &str = "target text";

The following code snippets do the same thing, at least on the surface:

// static impl
impl From<ZST> for &'static str {
  fn from(_: ZST) -> &'static str {
    TEXT
  }
}
// generic impl
impl<'a> From<ZST> for &'a str {
  fn from(_: ZST) -> &'a str {
    TEXT
  }
}

My question is:

  • Are they exactly the same? If not, what is the difference?
  • Which version takes more time to compile?

Since the reference is immutable and in return position, these are identical. That is, you can assign a &'static str to a variable that requires a &'a str , for any lifetime 'a . Likewise, either of these can be assigned to a variable that requires a shorter lifetime because a reference with a longer lifetime is a subtype.

In fact, the only possible way to implement impl<'a> From<ZST> for &'a str is to return a static. That's because it has to work for any 'a , and the only lifetime that satisfies that is 'static .

As for a difference in compile time, it will never be significant enough to worry about.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM