2013-05-07 5 views
8

테스트의 일부로 함수가 적절한 내용의 벡터를 반환한다고 주장하고 싶습니다. 따라서 예상 데이터를 정적 변수로 사용 가능하게 만들었습니다. 그러나 관리 벡터의 내용을 정적 벡터 변수와 비교하는 적절한 방법을 찾을 수 없습니다.중고 벡터의 내용과 녹의 정적 벡터를 비교하는 방법은 무엇입니까?

#[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()); 
} 

업데이트 :

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

:이 문제를 해결 작동 비교하기 전에 정적 벡터에 대한 참조를 할당, 그래서 나는 벡터의 평등을 주장하는 작은 매크로 결국 사용법 : assert_typed_eq([u8], my_data, expected_data);

+0

길이를 비교 한 다음 둘 다 반복 할 수 있습니다. 자신의 주장 매크로를 작성하십시오. –

답변

6

실제로 두 종류의 정적 벡터가 있습니다 : 고정 길이의 것들 ([u8, .. 3]) 및 정적 슬라이스 (&'static [u8])입니다. 전자는 다른 유형의 벡터와 아주 잘 상호 작용하지 않습니다. 후자는 여기에서 가장 유용합니다.

fn main() { 
    static x: &'static [u8] = &[1,2,3]; 

    let y = ~[1u8,2,3]; 
    assert_eq!(y.as_slice(), x); 
} 
+0

해명 해 주셔서 감사합니다. 나는 두 가지 종류의 정적 벡터가 있음을 몰랐다. 나는 로컬 타이프 된 참조 변수에 값을 먼저 할당 한 다음 assert_equal을 사용하는'assert_typed_eq'라는 새로운 매크로를 정의했다. 약간 불편한 것 같지만 지금은 잘 작동합니다. 타이! – Zargony

+0

당신은 어떤 버전의 녹이 사용 중인지 말하지 않습니다 -'vec :: eq'는 0.8으로 사라진 것 같습니다. –

+2

@AndrewAylett 확실히 있습니다. (우연히도, 나는 그것을했던 사람조차도 하하라고 생각한다.) 다행스럽게도 나는 수동으로 강제 변환을하기 위해 .as_slice()를 추가했다. 대답을 업데이트했다. – huon