简单的枚举应该派生出来吗?性能有什么不同吗?

时间:2017-06-22 09:17:31

标签: rust

use std::collections::HashMap;

// #[derive(Copy, Clone)]
enum SomeEnum {
    Some1,
    Some2,
}

struct SomeStruct {
    pub some_enum: SomeEnum,
    pub s: String,
}

fn proc_struct(some_struct: &SomeStruct) {
    let mut map = HashMap::new();
    map.insert(String::from("any"), 0);

    match map.get(&some_struct.s) { // just to make a reference in SomeStruct
        Some(v) => {
            proc1(some_struct.some_enum);
            proc2(&some_struct.some_enum);
        }
        None => {}
    }
}

fn proc1(some: SomeEnum) {}

fn proc2(some: &SomeEnum) {}

fn main() {
    let some_struct = SomeStruct { some_enum: SomeEnum::Some1, s: String::from("s") };

    proc_struct(&some_struct);
}

上面的代码产生以下错误:

error[E0507]: cannot move out of borrowed content
  --> src/main.rs:20:19
   |
20 |             proc1(some_struct.some_enum);
   |                   ^^^^^^^^^^^ cannot move out of borrowed content

当我将#[derive(Copy, Clone)]添加到SomeEnum时,它编译得很好。

SomeEnum这样的简单枚举是否应该得出Copy特征? 函数proc1()proc2()之间的性能是否存在差异?

1 个答案:

答案 0 :(得分:8)

引用docs

  

一般来说,如果您的类型可以实现Copy,那么它应该。

由于您的SomeEnum没有复合变体(例如VecString s),我建议Copy能够使用use std::mem; enum SomeEnum { Some1, Some2, } fn main() { assert_eq!(1, mem::size_of::<SomeEnum>()); assert_eq!(8, mem::size_of::<&SomeEnum>()); } 。看起来它实际上比对它的引用要小:

let mapview = GMSMapView.map(withFrame: CGRect.zero, camera: camera)

mapview.delegate = self


func mapView(_ mapView: GMSMapView, markerInfoWindow marker: GMSMarker) -> UIView? {
    // Get a reference for the custom overlay
    let index:Int! = Int(marker.accessibilityLabel!)
    let customInfoWindow = Bundle.main.loadNibNamed("CustomInfoWindow", owner: self, options: nil)?[0] as! CustomInfoWindow
    customInfoWindow.Timings.text = States[index].time
    customInfoWindow.Title.text = States[index].name
    customInfoWindow.Direction_Button.tag = index
    customInfoWindow.Direction_Button.addTarget(self, action: #selector(GetDirectionsAction(sender:)), for: .touchUpInside)

    return customInfoWindow
}

虽然我怀疑在这种情况下你将能够发现任何性能差异。