gpt4 book ai didi

rust - 为什么我们需要为 Option 变量调用 take()

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

在这段代码中:

pub struct Post {
state: Option<Box<dyn State>>,
content: String,
}

impl Post {
pub fn new() -> Post {
Post {
state: Some(Box::new(Draft {})),
content: String::new(),
}
}

pub fn add_text(&mut self, text: &str) {
self.content.push_str(text);
}

pub fn content(&self) -> &str {
""
}

pub fn request_review(&mut self) {
if let Some(s) = self.state.take() {
self.state = Some(s.request_review())
}
}
}

trait State {
fn request_review(self: Box<Self>) -> Box<dyn State>;
}

struct Draft {}

impl State for Draft {
fn request_review(self: Box<Self>) -> Box<dyn State> {
Box::new(PendingReview {})
}
}

struct PendingReview {
fn request_review(self: Box<Self>) -> Box<dyn State> {
self
}
}

调用take();书上说:

To consume the old state, the request_review method needs to take ownership of the state value. This is where the Option in the state field of Post comes in: we call the take method to take the Some value out of the state field and leave a None in its place.

We need to set state to None temporarily rather than setting it directly with code like self.state = self.state.request_review(); to get ownership of the state value. This ensures Post can’t use the old state value after we’ve transformed it into a new state.

如果我们直接设置 Post 怎么可能使用它的旧状态?

最佳答案

如果你这样编码:

pub struct Post {
state: Box<dyn State>,
content: String,
}

trait State {
fn request_review(self: Box<Self>) -> Box<dyn State>;
}

impl Post {
// ...
pub fn request_review(&mut self) {
self.state = self.state.request_review();
}
// ...
}

你会得到一个编译器错误:

self.state = self.state.request_review();
^^^^^^ move occurs because `self.state` has type `std::boxed::Box<dyn State>`, which does not implement the `Copy` trait'.

这是因为调用 State::request_review会搬家Box<self> ,这是在堆上分配的,除非你实现 Copy,否则 Rust 不允许你将值从堆中移走。 ,否则那里还剩下什么?本书使用Option::take()将所有权移出并离开None在这个地方。

关于rust - 为什么我们需要为 Option<T> 变量调用 take(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57193489/

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