Come parte di un test, voglio affermare che una funzione restituisce un vettore con contenuti corretti. Ho quindi reso disponibili i dati previsti come variabili statiche. Tuttavia, non riesco a trovare un modo corretto per confrontare il contenuto di un vettore gestito con la variabile vettoriale statica.Come confrontare i contenuti di un vettore di proprietà con un vettore statico in Rust?
#[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());
}
Aggiornamento: Assegnazione di un riferimento al vettore statica prima confrontandolo funziona in tutto il problema, quindi ho finito con una piccola macro per affermare l'uguaglianza di vettori:
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);
}))
Utilizzo: assert_typed_eq([u8], my_data, expected_data);
Si potrebbe confrontare lunghezze, e poi un ciclo su entrambi. Scrivi la tua macro di asserzione. –