为什么在设置响应体之前需要解引用 hyper 的 Response?

huangapple go评论85阅读模式
英文:

Why do I need to dereference hyper's Response before setting a body?

问题

在这里为您翻译代码部分:

let mut res = Response::new(Body::empty());
*res.body_mut() = Body::from("Ok, now...");

为什么在这里需要解引用呢?在这个上下文中,res 看起来不像一个指针,那么为什么 res.body_mut() = Body::from("Ok, now..."); 会引发以下错误?

error[E0070]: invalid left-hand side of assignment
--> src\main.rs:8:20
  |
8 |     res.body_mut() = Body::from("Ok, now...");
  |     -------------- ^
  |     |
  |     cannot assign to this expression
  |
help: consider dereferencing here to assign to the mutably borrowed value
  |
8 |     *res.body_mut() = Body::from("Ok, now...");
  |   

(注意:这只是代码的翻译,不包含其他内容。)

英文:

I'm getting started with Hyper (and Rust, in general) by following their guide. I noticed that before setting a body on the Response, I need to dereference it like this:

let mut res = Response::new(Body::empty());
*res.body_mut() = Body::from("Ok, now...");

Why is the dereferencing necessary here? res doesn't look like a pointer in this context, so why does res.body_mut() = Body::from("Ok, now...") throw the following error?

error[E0070]: invalid left-hand side of assignment
 --> src\main.rs:8:20
  |
8 |     res.body_mut() = Body::from("Ok, now...");
  |     -------------- ^
  |     |
  |     cannot assign to this expression
  |
help: consider dereferencing here to assign to the mutably borrowed value
  |
8 |     *res.body_mut() = Body::from("Ok, now...");
  |   

答案1

得分: 4

为什么在这里需要解引用?在这个上下文中,res 看起来不像一个指针,所以为什么 res.body_mut() = Body::from("Ok, now...") 会抛出以下错误?

并不是 res 是一个指针,而是 res.body_mut() 是一个指针:

pub fn body_mut(&mut self) -> &mut T

你需要解引用 &mut T 以替换指针指向的内容,否则你尝试将值分配给 res.body_mut() 本身,这... 没有太多意义。

Rust 的解引用运算符的优先级低于方法调用,因此方法调用首先执行。

英文:

> Why is the dereferencing necessary here? res doesn't look like a pointer in this context, so why does res.body_mut() = Body::from("Ok, now...") throw the following error?

It's not res which is a pointer, it's res.body_mut():

pub fn body_mut(&mut self) -> &mut T

you need to dereference the &mut T in order to replace the pointee, otherwise you try to assign to res.body_mut() itself which... doesn't make much sense.

Rust's dereference operator has a lower precedence than method calls, so the method call applies first.

huangapple
  • 本文由 发表于 2023年8月10日 15:59:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/76873716.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定