簡體   English   中英

將類型組合到枚舉中時如何從特征返回引用

[英]How to return a reference from a trait when combining types into enum

我有點卡住了(除了復制內存(請參閱游戲圍欄中的 DupKeyEAB),我得到了以下特征:

   pub trait KeyVal : Send + Sync + 'static { 
      type Key : Clone + Debug + 'static;
      fn get_key(&self) -> Self::Key;
      fn get_key_ref<'a>(&'a self) -> &'a Self::Key;
    }

我的問題是我需要類似的東西(以避免每次訪問密鑰時都使用克隆):

  pub trait KeyVal : Send + Sync + 'static { 
      type Key : Clone + Debug + 'static;
      type KeyRef<'_> : Debug;
      fn get_key(&self) -> Self::Key;
      fn get_key_ref<'a>(&'a self) -> Self::KeyRef<'a>;
    }

或直接(以KeyRef為特征)

  fn get_key_ref<'a,K : KeyRef<'a>>(&'a self) -> K;

要么

   fn get_key_ref<'a>(&'a self) -> KeyRef<'a>;

所有這些表示法顯然都是相當無效的,但它說明我需要返回與實現我的特征的結構具有相同生存期的引用,但與此同時,該引用不能只是&'a而是具有相同生存期的枚舉。

這樣,當在簡單的結構上使用get_key_ref時,我的KeyRef就是&'aKey,而在結合多個特征實現的枚舉上使用get_key_ref時(請參見EnumAB ),我可以在對鍵的引用上使用包裝枚舉:比如KeyABRef<'a>

  impl EnumAB {
     fn get_key_ok<'a>(&'a self) -> KeyABRef<'a> {
       match self {
         &EnumAB::A(ref a) => KeyABRef::A(a.get_key_ref()),
         &EnumAB::B(ref b) => KeyABRef::B(b.get_key_ref()),
       }
     }
   }

但是我無法將此功能納入我的特征。 我想知道是否有人針對這種需求找到了解決方案(KeyVal必須為“靜態”)?

我原來的測試代碼是:

use std::fmt::Debug;
use std::thread;

pub trait KeyVal : Send + Sync + 'static {
  type Key : Clone + Debug + 'static;
  fn get_key(&self) -> Self::Key;
  fn get_key_ref<'a>(&'a self) -> &'a Self::Key;
}

pub fn do_something_with_spawn<KV : KeyVal> (kv : KV) {
  thread::spawn ( move || {
    println!("{:?}", kv.get_key_ref());
  });
}
#[derive(Debug)]
pub struct StructA (usize);
#[derive(Debug)]
pub struct StructB (String);

#[derive(Debug)]
pub enum EnumAB {
  A(StructA),
  B(StructB),
}


impl KeyVal for StructA {
  type Key = usize;
  // type KeyRef<'_> = &'_ usize;
  fn get_key(&self) -> Self::Key {
    self.0.clone()
  }
  fn get_key_ref<'a>(&'a self) -> &'a Self::Key {
    &self.0
  }
}

impl KeyVal for StructB {
  type Key = String;
  // type KeyRef<'_> = &'_ String;
  fn get_key(&self) -> Self::Key {
    self.0.clone()
  }
  fn get_key_ref<'a>(&'a self) -> &'a Self::Key {
    &self.0
  }
}

#[derive(Clone,Debug)]
pub enum KeyAB {
  A(usize),
  B(String),
}

#[derive(Clone,Debug)]
pub enum KeyABRef<'a> {
  A(&'a usize),
  B(&'a String),
}

impl KeyVal for EnumAB {
  type Key = KeyAB;
  // type KeyRef<'_> = KeyABRef<'_>
  fn get_key(&self) -> Self::Key {
    match self {
      &EnumAB::A(ref a) => KeyAB::A(a.get_key()),
      &EnumAB::B(ref b) => KeyAB::B(b.get_key()),
    }
  }
  fn get_key_ref<'a>(&'a self) -> &'a Self::Key {
    panic!("cannot");
  }
}

impl EnumAB {
  fn get_key_ok<'a>(&'a self) -> KeyABRef<'a> {
    match self {
      &EnumAB::A(ref a) => KeyABRef::A(a.get_key_ref()),
      &EnumAB::B(ref b) => KeyABRef::B(b.get_key_ref()),
    }
  }
}

#[derive(Debug)]
pub struct DupKeyEAB (KeyAB, EnumAB);
impl KeyVal for DupKeyEAB {
  type Key = KeyAB;
  fn get_key(&self) -> Self::Key {
    self.0.clone()
  }
  fn get_key_ref<'a>(&'a self) -> &'a Self::Key {
    &self.0
  }
}

fn main () {
  let d2 = StructB("hello".to_string());
  let d3 = EnumAB::A(StructA(3));
  println!("{:?}",d2.get_key());
  println!("{:?}",d3.get_key());
  println!("{:?}",d2.get_key_ref());
  println!("{:?}",d3.get_key_ok());

 do_something_with_spawn(d3);
}

我同意AB的說法,即您的動機尚不明確,因此我們能提供的任何幫助充其量只能是猜測。 話雖如此,這是使用Borrow的猜測:

use std::borrow::Borrow;

trait KeyVal<'a> { 
    type Key: Borrow<Self::KeyRef>;
    type KeyRef: 'a;

    fn get_key(&self) -> Self::Key;
    fn get_key_ref(&'a self) -> &'a Self::KeyRef;
}

struct Example(u8);

impl<'a> KeyVal<'a> for Example {
    type Key = u8;
    type KeyRef = u8;

    fn get_key(&self) -> Self::Key {
        self.0
    }  

    fn get_key_ref(&'a self) -> &'a Self::KeyRef {
        &self.0
    }
}

fn main() {
    let e = Example(42);
    println!("{:?}", e.get_key());
    println!("{:p}", e.get_key_ref());
}

另一段是type KeyRef: 'a ,表示選擇的類型必須比'a壽命更長。

我想您不需要Borrow

trait KeyVal<'a> { 
    type Key;
    type KeyRef: 'a;

    fn get_key(&self) -> Self::Key;
    fn get_key_ref(&'a self) -> Self::KeyRef;
}

#[derive(Debug)]
struct Example(u8);
#[derive(Debug)]
struct RefWrapper<'a>(&'a u8);

impl<'a> KeyVal<'a> for Example {
    type Key = u8;
    type KeyRef = RefWrapper<'a>;

    fn get_key(&self) -> Self::Key {
        self.0
    }  

    fn get_key_ref(&'a self) -> Self::KeyRef {
        RefWrapper(&self.0)
    }
}

fn main() {
    let e = Example(42);
    println!("{:?}", e.get_key());
    println!("{:?}", e.get_key_ref());
}

使用Shepmaster的解決方案(加上HRTB生成),它變為:

use std::fmt::Debug;

use std::thread;

pub trait KeyVal<'a> : Send + Sync + 'static {
  type Key : Clone + Debug + 'static;
  type KeyRef : Debug + 'a;
  fn get_key(&self) -> Self::Key;
  fn get_key_ref(&'a self) -> Self::KeyRef;
}

pub fn do_something_with_spawn<KV> (kv : KV)
  where for <'a> KV : KeyVal<'a> {
  thread::spawn ( move || {
  println!("{:?}", kv.get_key_ref());
  });
}
#[derive(Debug)]
pub struct StructA (usize);
#[derive(Debug)]
pub struct StructB (String);

#[derive(Debug)]
pub enum EnumAB {
  A(StructA),
  B(StructB),
}


impl<'a> KeyVal<'a> for StructA {
  type Key = usize;
  type KeyRef = &'a usize;
  fn get_key(&self) -> Self::Key {
    self.0.clone()
  }
  fn get_key_ref(&'a self) -> Self::KeyRef {
    &self.0
  }
}

impl<'a> KeyVal<'a> for StructB {
  type Key = String;
  type KeyRef = &'a String;
  fn get_key(&self) -> Self::Key {
    self.0.clone()
  }
  fn get_key_ref(&'a self) -> Self::KeyRef {
    &self.0
  }
}

#[derive(Clone,Debug)]
pub enum KeyAB {
  A(usize),
  B(String),
}

#[derive(Clone,Debug)]
pub enum KeyABRef<'a> {
  A(&'a usize),
  B(&'a String),
}

impl<'a> KeyVal<'a> for EnumAB {
  type Key = KeyAB;
  type KeyRef = KeyABRef<'a>;
  fn get_key(&self) -> Self::Key {
    match self {
      &EnumAB::A(ref a) => KeyAB::A(a.get_key()),
      &EnumAB::B(ref b) => KeyAB::B(b.get_key()),
    }
  }
  fn get_key_ref(&'a self) -> Self::KeyRef {
    match self {
      &EnumAB::A(ref a) => KeyABRef::A(a.get_key_ref()),
      &EnumAB::B(ref b) => KeyABRef::B(b.get_key_ref()),
    }
  }
}



fn main () {
  let d2 = StructB("hello".to_string());
  let d3 = EnumAB::A(StructA(3));
  println!("{:?}",d2.get_key());
  println!("{:?}",d3.get_key());
  println!("{:?}",d2.get_key_ref());
  println!("{:?}",d3.get_key_ref());
  do_something_with_spawn(d3);

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM