为什么rustc说变量“totalSplitInv”超出范围?

时间:2015-01-31 07:05:26

标签: scope rust

我将以下程序运行到了rustc:

#![feature(slicing_syntax)]
fn sortAndCountInv(arr: &mut [i64]) -> i64 {
    return sortAndCountInv_(arr, 0, arr.length - 1)
}

fn sortAndCountInv_(arr: &mut [i64], start: i64, finish: i64) {
    let lengthOfSubarray = finish - start + 1;
    if (lengthOfSubarray == 0) || (lengthOfSubarray == 1) {
        return totalSplitInv
    }
    else {
        let half = (start + finish) / 2;
        let leftInv = sortAndCountInv_(arr, start, half);
        let rightInv = sortAndCountInv_(arr, half + 1, finish);
        let splitInv = mergeAndCountSplitInv(arr, start, finish, half);
        return leftInv + rightInv + splitInv
    }
}
fn mergeAndCountSplitInv(arr: &mut [i64], start: i64, finish: i64, half: i64) -> i64 {
    let aux = arr[start..finish + 1];
    let divider = half - start;
    let mut i = 0;
    let mut j = divider + 1;
    let mut totalSplitInv = 0;
    let lastIndex = aux.length - 1;
    for k in range(start, finish + 1) {
        if i > divider {
            arr[k] = aux[j];
            j += 1
        } else if j > lastIndex {
            arr[k] = aux[i];
            i += 1
        } else if aux[i] < aux[j] {
            arr[k] = aux[i];
            i += 1
        } else {
            arr[k] = aux[j];
            j += 1;
            totalSplitInv += (divider - i) + 1; 
        }
    }
    return totalSplitInv
}

当我尝试使用rustc v-0.12.0-dev编译它时,我收到以下范围错误:

inversions.rs:9:16: 9:29 error: unresolved name `totalSplitInv`.
inversions.rs:9         return totalSplitInv

也就是说,在函数mergeAndCountSplitInv中,行return totalSplitInv无效,因为totalSplitInv超出范围?为什么会这样?

1 个答案:

答案 0 :(得分:3)

我认为错误指的是return totalSplitInv中的sortAndCountInv_,而不是mergeAndCountSplitInv

fn sortAndCountInv_(arr: &mut [i64], start: i64, finish: i64) {
    let lengthOfSubarray = finish - start + 1;
    if (lengthOfSubarray == 0) || (lengthOfSubarray == 1) {
        return totalSplitInv // here
...