为什么&Box<ListNode>可以赋值给&ListNode?
why can &Box<ListNode> be assigned to &ListNode?
我发现 &Box<ListNode>
类型的变量可以赋值给 &ListNode
类型的变量。它们是不同的类型,我不知道这背后的机制。我认为这可能是因为 Deref coercion
。但我认为 Deref corecion
只出现在 methold 解决方案或参数传递中。我不知道。有人可以帮我吗?非常感谢。
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;
}
你是对的,这是因为 Deref
coercion. Coercions can be done at any coercion site 包括 "let
给出显式类型的语句".
我发现 &Box<ListNode>
类型的变量可以赋值给 &ListNode
类型的变量。它们是不同的类型,我不知道这背后的机制。我认为这可能是因为 Deref coercion
。但我认为 Deref corecion
只出现在 methold 解决方案或参数传递中。我不知道。有人可以帮我吗?非常感谢。
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;
}
你是对的,这是因为 Deref
coercion. Coercions can be done at any coercion site 包括 "let
给出显式类型的语句".