implement a list using Rust
2023-09-27 14:21:05 时间
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); } } }
相关文章
- leetcode 382 Linked List Random Node
- C#对泛型List<T>系列化与反系列化
- SharePoint 如何找到List的Template ID
- 解决idea创建maven项目时一直显示“Loading archetype list ”
- 【Rust】格式化输出-List
- initialization list,initializer list,uniform initialization的区别
- apt系统中sources.list文件的解析
- MyBatis传入参数为list、数组、map写法
- 142. Linked List Cycle II
- List()接口
- SyntaxError: missing ) after argument list
- Python NumPy相对于list列表的优势介绍
- Java 使用一行代码初始化ArrayList或List的方法代码
- Github遇到Permanently added the RSA host key for IP address '192.30.252.128' to the list of known host
- [LeetCode] 86. Partition List 划分链表