PFA hard
PFA hard

Reputation: 91

Unexpected behavior "for in n..m" in Rust

I faced with unexpected behavior. I tried to figure it out myself with the debug, but it doesn't help. P.S. sorry if problem will be something stupid.

src/main.rs

use test_crate::radix_tree_1::Node;

fn main() {
    let mut node = Node {
        label: String::from("test.com"),
        nodes: Vec::new(),
    };
    node.insert(String::from("test.com/company"));
    println!("{:?}",node);
}

src/radix_tree_1.rs

#[derive(Debug)]
pub struct Node {
    pub label: String,
    pub nodes: Vec<Node>,
}

//current node:
//let mut node = Node {
//    label: "test.com",
//    nodes: Vec::new(),
//};
impl Node {
    pub fn insert(&mut self, s: String) {
        //inserting test.com/comapany
        let parts: Vec<String> = s.split("/").map(|x| String::from(x)).collect();
        //parts [test.com,company]
        let parts_len = parts.len();
        //parts_len 2
        let mut reached: String = String::new();
        //reached ""
        let prefixs: Vec<String> = self.label.split("/").map(|x| String::from(x)).collect();
        //prefixs [test.com] from self.label = test.com
        let prefixs_len = prefixs.len();
        //prefixs_len = 1
        println!("{:?}, {:?}, {}",parts, prefixs, parts_len);
        for index in 0..parts_len-1 {
        // for index 0,1
            println!("index {}", index);
            if index >= prefixs_len {
            // if 0 >= 1
                println!("i>=prefixs.len");
                self.nodes.push(Node {
                    label: parts[index..].iter()
                        .map(|s| {
                            String::from(s)
                        }).collect(),
                    nodes: Vec::new(),
                })
            } else {
            // else
                if parts[index] == prefixs[index] {
                //if test.com == test.com
                    reached.push_str(prefixs[index].as_str());
                    // reached = test.com
                    println!("{}",reached);
                } else {
                    println!("parts[index] != prefixs[index]");
                }
            }
        }
    }
}

I spam with println! and comment in code to debug, i don't delete them to your better understand. This concole output:

["test.com", "company"], ["test.com"], 2
index 0
test.com
Node { label: "test.com", nodes: [] }

expectation: reach index --- 1

reality: "for" work only with index --- 0

Where is problem?

Upvotes: 0

Views: 48

Answers (1)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230276

Range .. is exclusive already (doesn't include the end value), no need to subtract 1 on top of it.

Upvotes: 3

Related Questions