• implement a list using Rust


    Rust果然比較複雜,在經歷了n次compile fail,終于寫成了一個 list

    難點: 對Rc<>的用法不熟悉。對borrow checker不夠熟悉

    有些寫法可能還不是最短的

    use std::rc::Rc;
    
    fn main() {
        println!("Hello, world!");
    
        let li = ListInternal {
            data: 1,
            next: None,
        };
        let li = ListInternal {
            data: 2,
            next: Some(Rc::new(li)),
        };
    
        let mut l = List { next: Some(li) };
    
        for i in 1..10{
            l.push_back(i);
        }
        
        l.print();
    }
    
    struct ListInternal {
        data: i32,
        next: Option<Rc<ListInternal>>,
    }
    
    struct List {
        next: Option<ListInternal>,
    }
    
    impl ListInternal {
        fn print(&self) {
            println!("{}", self.data);
    
            if let Some(ref v) = self.next {
                v.print();
            }
        }
    
        fn print_loop(&self) {
            let mut t = self;
            loop {
                println!("{}", t.data);
    
                if let Some(ref v) = t.next {
                    t = v;
                } else {
                    break;
                }
            }
        }
    
        fn last(&mut self) -> &mut Self {
            let mut t = self;
            loop {
                if let Some(ref mut v) = t.next {
                    t = Rc::get_mut(v).unwrap();
                } else {
                    break;
                }
            }
            t
        }
    }
    impl List {
        fn new() -> List {
            List { next: None }
        }
    
        fn print(&self) {
            if let Some(ref v) = self.next {
                v.print_loop();
            }
        }
        fn push_back(&mut self, data: i32) {
            let li = ListInternal {
                data: data,
                next: None,
            };
    
            if let Some(ref mut v) = self.next {
                v.last().next = Some(Rc::new(li));
            } else {
                self.next = Some(li);
            }
        }
    }
    
  • 相关阅读:
    通过Internet使用VSS2005
    基于角色的权限设计(一)
    WFF架构及技术
    WFF概述
    企业库:Cache
    权限设计(二)
    应用系统中的编码和编码规则
    希望更多的人也可以来应用wordpress程序
    说说我的一点小感受了
    思维决定命运
  • 原文地址:https://www.cnblogs.com/cutepig/p/11459177.html
Copyright © 2020-2023  润新知