gpt4 book ai didi

rust - 是否有任何机制可以使用 Rust 或 Rust 工具生成 "ownership tree"可视化?

转载 作者:行者123 更新时间:2023-11-29 08:00:48 25 4
gpt4 key购买 nike

"Programming Rust" by Jim Blandy & Jason Orendorff 的第 4 章中它说,

It follows that the owners and their owned values form trees: your owner is your parent, and the values you own are your children. And at the ultimate root of each tree is a variable; when that variable goes out of scope, the entire tree goes with it. We can see such an ownership tree in the diagram for composers: it’s not a “tree” in the sense of a search tree data structure, or an HTML document made from DOM elements. Rather, we have a tree built from a mixture of types, with Rust’s single-owner rule forbidding any rejoining of structure that could make the arrangement more complex than a tree. Every value in a Rust program is a member of some tree, rooted in some variable.

提供了一个例子,

Rust Ownership Tree

这很简单也很漂亮,但是是否有任何机制可以使用 Rust 或 Rust 工具生成“所有权树”可视化?我可以在调试时转储所有权树吗?

最佳答案

并没有真正的特定工具,但您可以通过派生 Debug 特性来获得非常接近的效果。当您为结构派生 Debug 特性时,它将为您提供所有拥有数据的递归表示,终止于原始类型,例如 stru32 等,或者当它遇到自定义 Debug 实现时。例如,这里的程序:

use rand;

#[derive(Debug)]
enum State {
Good,
Bad,
Ugly(&'static str),
}

#[derive(Debug)]
struct ExampleStruct {
x_factor: Option<f32>,
children: Vec<ExampleStruct>,
state: State,
}

impl ExampleStruct {
fn random(max_depth: usize) -> Self {
use rand::Rng;
let mut rng = rand::thread_rng();

let child_count = match max_depth {
0 => 0,
_ => rng.gen::<usize>() % max_depth,
};

let mut children = Vec::with_capacity(child_count);

for _ in 0..child_count {
children.push(ExampleStruct::random(max_depth - 1));
}

let state = if rng.gen() {
State::Good
} else if rng.gen() {
State::Bad
} else {
State::Ugly("really ugly")
};

Self {
x_factor: Some(rng.gen()),
children,
state,
}
}
}

fn main() {
let foo = ExampleStruct::random(3);
dbg!(foo);
}

打印出这样的东西:

[src/main.rs:51] foo = ExampleStruct {
x_factor: Some(
0.27388978,
),
children: [
ExampleStruct {
x_factor: Some(
0.5051847,
),
children: [
ExampleStruct {
x_factor: Some(
0.9675246,
),
children: [],
state: Ugly(
"really ugly",
),
},
],
state: Bad,
},
ExampleStruct {
x_factor: Some(
0.70672345,
),
children: [],
state: Ugly(
"really ugly",
),
},
],
state: Bad,
}

请注意,并非所有数据都是一致的: children 住在堆上的其他地方。它们不存储在 ExampleStruct 中,它们只是由它拥有。

如果您存储对事物的引用,这可能会造成混淆,因为调试可能会开始遍历这些引用。调试它们不被拥有并​​不重要。其实State::Ugly里面的&'static str就是这样的。组成字符串的实际字节不属于任何变量,它们是硬编码的并且存在于程序本身中。只要程序运行,它们就会存在。

关于rust - 是否有任何机制可以使用 Rust 或 Rust 工具生成 "ownership tree"可视化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57487568/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com