简体   繁体   English

将类型组合到枚举中时如何从特征返回引用

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

I am a bit stuck (except by duplicating my memory (see DupKeyEAB in playpen ), I got this trait: 我有点卡住了(除了复制内存(请参阅游戏围栏中的 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;
    }

My problem is that I need something like (to avoid using clone each time I access the 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>;
    }

or directly (with KeyRef as a trait) 或直接(以KeyRef为特征)

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

or 要么

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

All those notations are obviously pretty invalid, but it illustrate that I need to return a reference with the same lifetime as the struct implementing my trait but at the same time the reference could not simply be &'a but also a enum with the same lifetime. 所有这些表示法显然都是相当无效的,但它说明我需要返回与实现我的特征的结构具有相同生存期的引用,但与此同时,该引用不能只是&'a而是具有相同生存期的枚举。

That way when using get_key_ref on simple struct my KeyRef is simply &'aKey and when using get_key_ref on enum combining multiple trait implementation (see EnumAB ) I could use a wrapper enum over the reference to the key : like KeyABRef<'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()),
       }
     }
   }

Yet I cannot include this function in my trait. 但是我无法将此功能纳入我的特征。 I wonder if anyone got a solution for this kind of need (KeyVal need to be 'static)? 我想知道是否有人针对这种需求找到了解决方案(KeyVal必须为“静态”)?

My original test code was : 我原来的测试代码是:

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);
}

I agree with AB that your motivation is unclear, so any help we can provide is guessing at best. 我同意AB的说法,即您的动机尚不明确,因此我们能提供的任何帮助充其量只能是猜测。 That being said, here's a guess that uses Borrow : 话虽如此,这是使用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());
}

The other piece is type KeyRef: 'a , which indicates that the type chosen must outlive 'a . 另一段是type KeyRef: 'a ,表示选择的类型必须比'a寿命更长。

You don't need Borrow though, I suppose: 我想您不需要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());
}

Using Shepmaster's solution (plus HRTB for spawn), it becomes : 使用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