gpt4 book ai didi

rust - 如何重用结构的公共(public)代码?

转载 作者:行者123 更新时间:2023-12-03 11:33:07 30 4
gpt4 key购买 nike

我想为结构重用代码。例如:

use std::fmt::Display;

struct CommonStruct<T: Display> {
// could have more fields
data: T
}

struct A<T: Display> {
com: CommonStruct<T>,
age: i32
}

struct B<T: Display> {
com: CommonStruct<T>,
name: String
}

impl<T: Display> A<T> {
// could be more common functions
fn print_data(&self) {
// could be more complicated
println!("data: {}", self.com.data);
}
}

impl<T: Display> B<T> {
// could be more common functions
fn print_data(&self) {
// could be more complicated
println!("data: {}", self.com.data);
}
}

fn main() {
let a = A{ com: CommonStruct{data: 10}, age: 0 };
a.print_data();
let b = B{ com: CommonStruct{data: 12}, name: "123".to_string() };
b.print_data();
}

其中 AB 有一些由 CommonStruct 封装的公共(public)字段和一些公共(public)函数(例如,print_data ).

我尝试使用 trait 但找不到解决方案:

use std::fmt::Display;

struct CommonStruct<T: Display> {
// could have more fields
data: T
}

struct A<T: Display> {
com: CommonStruct<T>,
age: i32
}

struct B<T: Display> {
com: CommonStruct<T>,
name: String
}

trait Common {
// could be more common functions
fn print_data(&self) {
print_data(&self)
}
}

impl<T: Display> Common for A<T> {
}

impl<T: Display> Common for B<T> {
}

fn print_data(t: &Common) {
// could be more complicated
println!("data: {}", t.com.data);
}

fn main() {
let a = A{ com: CommonStruct{data: 10}, age: 0 };
a.print_data();
let b = B{ com: CommonStruct{data: 12}, name: "123".to_string() };
b.print_data();
}

最佳答案

由于 print_data 只使用了 CommonStruct,A 和 B 没有共享其他字段,所以将其作为 CommonStruct 的实现并直接调用它。

impl <T: Display> CommonStruct<T> {
fn print_data(&self) {
println!("data: {}", self.data);
}
}

fn main() {
let a = A{ com: CommonStruct{data: 10}, age: 0 };
a.com.print_data();
let b = B{ com: CommonStruct{data: 12}, name: "123".to_string() };
b.com.print_data();
}

或者,创建一个具有 print_data 的具体实现的特征,它依赖于获取数据的方法。

trait HasData<T: Display> {
fn get_data(&self) -> &T;
fn print_data(&self) {
// could be more complicated
println!("data: {}", self.get_data());
}
}

然后每个人只需要实现如何获取数据。

impl<T: Display> HasData<T> for CommonStruct<T> {
fn get_data(&self) -> &T {
return &self.data;
}
}

impl<T: Display> HasData<T> for A<T> {
fn get_data(&self) -> &T {
return &self.com.data;
}
}

impl<T: Display> HasData<T> for B<T> {
fn get_data(&self) -> &T {
return &self.com.data;
}
}

fn main() {
let a = A{ com: CommonStruct{data: 1}, age: 0 };
a.print_data();
let b = B{ com: CommonStruct{data: 2}, name: "123".to_string() };
b.print_data();
let c = CommonStruct{data: 3};
c.print_data();
}

关于rust - 如何重用结构的公共(public)代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64733353/

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