說,我有以下代碼:
use std::ptr::NonNull;
use std::marker::PhantomPinned;
use std::pin::Pin;
#[derive(Debug)]
struct Unmovable {
data: Vec<String>,
cache: Option<NonNull<String>>,
_pin: PhantomPinned,
}
impl<'a> Unmovable {
pub fn new(data: Vec<String>) -> Pin<Box<Self>> {
let internal = Self {
data,
cache: None,
_pin: PhantomPinned
};
let mut boxed = Box::pin(internal);
let cache = if boxed.data.len() > 0 {
Some(NonNull::from(&boxed.data[0]))
} else {
None
};
unsafe {
let ref_mut: Pin<&mut Unmovable> = Pin::as_mut(&mut boxed);
Pin::get_unchecked_mut(ref_mut).cache = cache;
}
boxed
}
pub fn get_cache(&'a self) -> Option<&'a String> {
Some(unsafe { self.cache?.as_ref() })
}
}
fn main() {
let unm = Unmovable::new(vec!["hello".to_owned(), "there".to_owned()]);
println!("{:?}", unm);
println!("{:?}", unm.get_cache());
}
new我想知道,該函式是在通用指定的塊中實作還是在沒有該通用引數的情況下單獨實作,是否有任何區別impl,因為它沒有在那里使用。說實話,我有點驚訝 Rust 確實允許這樣做,實作一個不使用所有泛型的函式,因為它被禁止用于結構,例如。所以我很好奇這種混合宣告是否有一些含義。
該new函式是否等同于旁邊沒有泛型的單獨實作impl?
uj5u.com熱心網友回復:
型別引數或 const 泛型將不允許使用它。但是允許 impl 上的免費生命周期。只有在關聯型別中使用時才不允許使用它們。源代碼中解釋了基本原理:
// (*) This is a horrible concession to reality. I think it'd be
// better to just ban unconstrained lifetimes outright, but in
// practice people do non-hygienic macros like:
//
// ```
// macro_rules! __impl_slice_eq1 {
// ($Lhs: ty, $Rhs: ty, $Bound: ident) => {
// impl<'a, 'b, A: $Bound, B> PartialEq<$Rhs> for $Lhs where A: PartialEq<B> {
// ....
// }
// }
// }
// ```
//
// In a concession to backwards compatibility, we continue to
// permit those, so long as the lifetimes aren't used in
// associated types. I believe this is sound, because lifetimes
// used elsewhere are not projected back out.
我對 rustc 的內部結構知之甚少,無法肯定地說,但我很確定它不會影響任何事情。最好不要使用它;在需要它的方法上使用生命周期,而不是在 impl 上。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/480197.html
下一篇:不能宣布歧視聯盟的成員
