gpt4 book ai didi

module - 我不能在同一个文件中拥有所有特征和 impl;如何放在单独的文件中?

转载 作者:行者123 更新时间:2023-11-29 08:15:40 27 4
gpt4 key购买 nike

我在顶层文件中有一个结构、一个特征和一个 impl。

struct Model {}

trait TsProperties {
fn create_ar_x_matrix(&self);
}

impl TsProperties for Model {
fn create_ar_x_matrix(&self){}
}

我想将 trait 和 impl 移动到一个名为 test.rs 的单独文件中。在我的主文件中:

mod test

在测试中我有:

use crate::Model;

当我实例化该结构时,Intellisense 没有选择 create_ar_x_matrix。如果代码在 main.rs 中,它确实如此。

我该如何解决?

如果我添加 pub 我会得到这个错误:

25 | pub impl TsProperties for Model {                                                                                                                        
| ^^^ `pub` not permitted here because it's implied

如果我在主文件的结构上使用 pub 并将特征放在一个单独的文件中:

error[E0599]: no method named `create_ar_x_matrix` found for type `Model` in the current scope                                                                         
--> src/main.rs:353:12
|
64 | pub struct Model {
| --------------------- method `create_ar_x_matrix` not found for this

最佳答案

您需要导入特征。

test.rs中:

use crate::Model;

pub trait TsProperties {
fn create_ar_x_matrix(&self);
}

impl TsProperties for Model {
fn create_ar_x_matrix(&self){}
}

main.rs 中:

mod test;
use self::test::TsProperties;

struct Model {}

fn main() {
let model = Model {};
model.create_ar_x_matrix();
}

请注意,Model 不需要公开,但 trait 需要公开。这是因为父模块中的任何内容在子模块中自动可见。

关于module - 我不能在同一个文件中拥有所有特征和 impl;如何放在单独的文件中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54168394/

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