Rust 的所有权系统(Ownership)是内存安全的革命性设计。
Rust 的所有权三原则
- 每个值有且只有一个所有者
- 所有者离开作用域,值被 drop
- 借用检查器确保引用安全
Python 的引用计数
Python 使用引用计数 + 垃圾回收。
常见陷阱
循环引用
python
class Node:
def __init__(self):
self.parent = None
self.children = []
def add_child(self, child):
child.parent = self # 循环引用!
self.children.append(child)解决方案:使用 weakref。
结论
Rust 在编译期保证内存安全,Python 在运行期处理。
评论
0评论加载中…