[英]Is there some syntactic sugar for matching on deeply nested Option and Result chains?
[英]Composition over inheritance, sure, but do we have any syntactic sugar for the function passthrough boilerplate?
如果我有一個實現特征的結構,然后將該結構封裝在另一個結構中,是否有一種簡單的方法可以通過所有 function 調用來為第二個結構實現該特征?
trait HasAnX {
fn get_x(&self) -> i32;
}
struct StructA {
x: i32
}
impl HasAnX for StructA {
fn get_x(&self) -> i32 {
self.x
}
}
struct StructB {
a: StructA
}
// This is the part I don't want to have to write out for every function in StructA
impl HasAnX for StructB {
fn get_x(&self) -> i32 {
self.a.get_x()
}
}
我認為一半的問題是我什至不確定這個問題叫什么。
為StructB
實現HasAnX
的需要通常來自於考慮 inheritance 的問題。 為避免這種情況,請嘗試只處理您真正關心的部分。
如果你只想調用a
方法,你可以從外部這樣做:
struct_b.a.get_x();
如果你想使用像StructA
這樣的東西,你可以只為它實現AsRef<StructA>
,同樣你可以使用AsMut
進行可變訪問。 然后函數可以只接受一個impl AsRef<StructA>
而不需要關心它是什么實際類型,還有一個額外的好處,它現在也可以接受擁有的類型和引用。
impl AsRef<StructA> for StructB {
fn as_ref(&self) -> &StructA {
&self.a
}
}
// you can pass in any of `StructA`, `&StructA`, `StructB`, `&StructB`
pub fn reads_from_a(a: impl AsRef<StructA>) {
let a = a.as_ref();
println!("{}", a.get_x());
}
如果您的StructB
是一種智能指針,您可以實現Deref
並直接在StructB
上使用StructA
的方法
use std::ops::Deref;
impl Deref for StructB {
type Target = StructA;
fn deref(&self) -> &StructA {
&self.a
}
}
//...
struct_b.get_x();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.