gpt4 book ai didi

rust - 如何在const fn new()中将结构的字段设置为None?

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

我正在学习Writing an OS in Rust类(class),并遇到了结构初始化的一个问题:

struct ListNode {
size: usize,
next: Option<&'static mut ListNode>,
}

impl ListNode {

const fn new(size: usize) -> Self {
ListNode { size, next: None }
}

fn start_addr(&self) -> usize {
self as *const Self as usize
}

fn end_addr(&self) -> usize {
self.start_addr() + self.size
}
}

我无法将 None分配给 next字段的问题是可变引用:
error[E0723]: mutable references in const fn are unstable
--> src/allocator/linked_list.rs:14:32
|
14 | ListNode { size, next: None }
| ^^^^
|

最佳答案

在您粘贴的代码段之后的下一段中对此进行了说明:

The type has a simple constructor function named new and methods to calculate the start and end addresses of the represented region. We make the new function a const function, which will be required later when constructing a static linked list allocator. Note that any use of mutable references in const functions (including setting the next field to None) is still unstable. In order to get it to compile, we need to add #![feature(const_fn)] to the beginning of our lib.rs.

关于rust - 如何在const fn new()中将结构的字段设置为None?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61732576/

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