How to compare contents belonging to a vector with a static vector in Rust?

As part of the test, I want to argue that the function returns a vector with the appropriate content. Therefore, I made the expected data available as static variables. However, I cannot find a suitable way to compare the contents of a managed vector with a static vector variable.

#[test] fn test_my_data_matches_expected_data () { static expected_data: [u8, ..3] = [1, 2, 3]; let my_data: ~[u8] = ~[1, 2, 3]; // actually returned by the function to test // This would be obvious, but fails: // -> mismatched types: expected `~[u8]` but found `[u8 * 3]` assert_eq!(my_data, expected_data); // Static vectors are told to be available as a borrowed pointer, // so I tried to borrow a pointer from my_data and compare it: // -> mismatched types: expected `&const ~[u8]` but found `[u8 * 3]` assert_eq!(&my_data, expected_data); // Dereferencing also doesn't work: // -> type ~[u8] cannot be dereferenced assert_eq!(*my_data, expected_data); // Copying the static vector to a managed one works, but this // involves creating a copy of the data and actually defeats // the reason to declare it statically: assert_eq!(my_data, expected_data.to_owned()); } 

Update: Assigning a reference to a static vector before matching it works around the problem, so I ended up with a small macro to state the equality of vectors:

 macro_rules! assert_typed_eq (($T: ty, $given: expr, $expected: expr) => ({ let given_val: &$T = $given; let expected_val: &$T = $expected; assert_eq!(given_val, expected_val); })) 

Usage: assert_typed_eq([u8], my_data, expected_data);

+8
comparison types static vector rust
source share
1 answer

In fact, there are two types of static vectors: fixed lengths ( [u8, .. 3] ) and static slices ( &'static [u8] ). The first one does not interact well with other types of vectors. The latter is most useful here:

 fn main() { static x: &'static [u8] = &[1,2,3]; let y = ~[1u8,2,3]; assert_eq!(y.as_slice(), x); } 
+6
source share

All Articles