'why can &Box<ListNode> be assigned to &ListNode?
I found a variable of type &Box<ListNode> can be assigned to a variable of type &ListNode. They are different types, I don't known the mechanism behind this. I thought it might because of the Deref coercion. But I think Deref corecion only occurs in methold solution or parameter passing. I am not sure. Could someone help me? Thanks you very much.
pub struct ListNode {
pub val: i32,
pub next: Option<Box<ListNode>>
}
impl ListNode {
#[inline]
fn new(val: i32) -> Self {
ListNode {
next: None,
val
}
}
}
fn f1() {
let node = ListNode::new(0);
let mut ref_node:&ListNode = &node;
let mut ref_box :&Box<ListNode>= &Box::new(ListNode::new(10));
// why &Box<ListNode> can be assign to &ListNode?
ref_node = ref_box;
}
Solution 1:[1]
You are correct that this is because of Deref coercion. Coercions can be done at any coercion site which includes "let statements where an explicit type is given".
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | kmdreko |
