gpt4 book ai didi

struct - 如何在Rust中实现一个具有自身作为字段的列表的结构

转载 作者:行者123 更新时间:2023-12-03 11:41:14 25 4
gpt4 key购买 nike

我已经开始学习Rust,目前正在尝试编写一个小的神经网络作为个人练习。我想为即将到来的“层/集群/节点组”定义一个结构。我的初始定义如下所示:

struct Layer {
name: String, // Human readable name
id: String, // UUID in the future
order: u8, // int for sorting
width: u8, // Number of nodes
input: [&'Self], // References to other Layers that feed input into this
}

我正在努力的事情是 input字段,该字段应包含对其他Layer-instance的引用的列表。我会在编译时知道列表中每个图层有多少个,所以我不必更改。是否有可能做到这一点?我无法在Google机器或“书”中找到解决方案。

请指教。

最佳答案

Is it possible to do this? I cant find a solution on the Google machine or in "the book".



可能是的,尽管我不建议这样做。

让我们从可能的开始: &Self将是一个具有未命名生命周期的“层引用”,生命周期名称以 '<symbol>的形式表示,因此,当您编写 &'Self时,您要指定生命周期 'Self的引用,但您永远都不会指定被引用的类型,这就是为什么rustc提示“期望类型”的原因。

如果添加“适当的”生存期名称,并对其结构进行参数化,则可以正常编译:

struct Layer<'sublayers> {
name: String, // Human readable name
id: String, // UUID in the future
order: u8, // int for sorting
width: u8, // Number of nodes
input: [&'sublayers Self], // References to other Layers that feed input into this
}

但是,我不建议您这样做,因为最后一个成员是切片,这意味着它是 DST,很难在最好的时间使用它-正如nomicon特别指出的那样,“自定义DST到目前为止基本上是半生不熟的功能”。

由于Rust还没有合适的const泛型,所以您也不能使用通过 layer参数化的数组(例如 Layer<const Size>input: [&Self;Size],也许有一天),因此您可能想要像矢量或切片引用之类的东西。

struct Layer<'slice, 'sublayers: 'slice> {
name: String, // Human readable name
id: String, // UUID in the future
order: u8, // int for sorting
width: u8, // Number of nodes
input: &'slice [&'sublayers Self], // References to other Layers that feed input into this
}

关于struct - 如何在Rust中实现一个具有自身作为字段的列表的结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62422857/

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