How to avoid temporary allocations when using a complex key for a HashMap?

后端 未结 2 1278
栀梦
栀梦 2020-11-30 11:23

I\'m using a complex key for HashMap such that the key comprises two parts and one part is a String, and I can\'t figure out how to do lookups via

2条回答
  •  自闭症患者
    2020-11-30 11:55

    It sounds like you want this.

    Cow will accept a &str or String.

    use std::borrow::Cow;
    
    #[derive(Debug, Eq, Hash, PartialEq)]
    struct Complex<'a> {
        n: i32,
        s: Cow<'a, str>,
    }
    
    impl<'a> Complex<'a> {
        fn new>>(n: i32, s: S) -> Self {
            Complex { n: n, s: s.into() }
        }
    }
    
    fn main() {
        let mut m = std::collections::HashMap::, i32>::new();
        m.insert(Complex::new(42, "foo"), 123);
    
        assert_eq!(123, *m.get(&Complex::new(42, "foo")).unwrap());
    }
    

    A comment about lifetime parameters:

    If you don't like the lifetime parameter and you only need to work with &'static str or String then you can use Cow<'static, str> and remove the other lifetime parameters from the impl block and struct definition.

提交回复
热议问题