traits 相关问题

在计算机编程中,特征是一组方法,用作“构建面向对象程序的简单概念模型”

如何在 Vec 上实现可以附加字符串的特征?

这是来自尝试 Rustlings 运动特征 2。该练习要求我在 Vec 上实现该特征。测试已经存在,但它们失败了,这是一个很好的起点。我已经做到了这一点

回答 4 投票 0

如何允许自定义类型的 Vec 与 &str 连接?

我希望 Vec 可以通过 &str 连接。这是我到目前为止所尝试过的: #[导出(调试)] 结构项目{ 字符串:字符串, } 实现项目 { pub fn new(字符串: impl Into 我希望 Vec<CustomType> 可以被 &str 加入。这是我到目前为止所尝试过的: #[derive(Debug)] struct Item { string: String, } impl Item { pub fn new(string: impl Into<String>) -> Self { Self { string: string.into(), } } pub fn to_string(&self) -> &String { &self.string } } impl From<&Item> for &String { fn from(item: &Item) -> Self { &item.string } } impl From<&Item> for &str { fn from(item: &Item) -> Self { &item.string.to_string() } } fn main() { let items = Vec::from([Item::new("Hello"), Item::new("world")]); let string = items.join(" "); println!("{}", string); } 这会导致错误: $ rustc jointrait.rs error[E0599]: the method `join` exists for struct `Vec<Item>`, but its trait bounds were not satisfied --> jointrait.rs:32:24 | 32 | let string = items.join(" "); | ^^^^ method cannot be called on `Vec<Item>` due to unsatisfied trait bounds | = note: the following trait bounds were not satisfied: `[Item]: Join<_>` rustc 帮助只是说缺少某些方法,但是通过谷歌搜索错误,我找不到我需要实现哪个方法/特征。 为了使 T 列表可连接,[T] 需要实现 Join<Separator>。 如果你查看哪些东西已经实现了Join,你会发现以下条目: impl<S> Join<&str> for [S] where S: Borrow<str> 这意味着,所有实现 Borrow<str> 的内容都可以通过 &str 分隔符连接起来。所以你所要做的就是为你的结构实现Borrow<str>: use std::borrow::Borrow; #[derive(Debug)] struct Item { string: String, } impl Item { pub fn new(string: impl Into<String>) -> Self { Self { string: string.into(), } } } impl Borrow<str> for Item { fn borrow(&self) -> &str { &self.string } } fn main() { let items = Vec::from([Item::new("Hello"), Item::new("world")]); let string = items.join(" "); println!("{}", string); } Hello world

回答 1 投票 0

用于实现获取结构体 id 的特征规范

我有一个关于特定特征的定义的问题。基本上我想定义一个特征,它提供一个函数来获取可以识别它的结构的 id (或键)。 然而,我...

回答 1 投票 0

为什么使用嵌套特征会改变 PHP 行为?

使用 PHP 7.2,我有一个类 MyClass,它使用特征 MyFirstTrait。它的定义如下: 我的班级 { 使用我的第一特征; } 此 MyFirstTrait 使用另一个特征 MySecondTrait。这是德...

回答 2 投票 0

未找到 Laravel 自定义特征

我对特质很陌生,但我想尝试一下。但是,它似乎没有加载。 我在 Laravel 应用程序目录下的文件夹中创建了一个名为 CheckPermsAgainstObjectTra...

回答 8 投票 0

构建一个常量通用钳位函数

所以我有 usize 和 f32 的 const 钳位函数。逻辑很简单:它只是将 val 与 low 和 high 进行比较,然后返回范围内的合适值: // 你可能有...

回答 1 投票 0

在 Rust 中管理多个连接池

我正在使用 Rust 中的 Salvo Web 框架构建一个应用程序。该应用程序将具有多种类型的数据库连接(postgres no tls、postgres with tls、redis no tls、redis with tls)。这将是用户定义的

回答 1 投票 0

php 特性使用另一个特性

我有一个特征正在使用另一个特征,现在我收到了有关类中不存在的函数的错误。 我简化了代码: 设置.php 我有一个特征正在使用另一个特征,现在我收到了有关类中不存在的函数的错误。 我简化了代码: settings.php <?php trait settings { // read setting from config.ini protected function getSetting($type, $setting){ try { $configFile = dirname(__FILE__)."/../config.ini"; if (!file_exists($configFile) || !is_file($configFile)) throw new Exception("Config file was not found. "); $configContents = parse_ini_file($configFile,true); if (is_array($configContents) && array_key_exists($type, $configContents) && is_array($configContents[$type]) && array_key_exists($setting, $configContents[$type])) return $configContents[$type][$setting]; else throw new Exception("Setting ".$setting." could not be found in ".$type."."); } catch (Exception $e) { throw new Exception($e->getMessage()); } } } database.php <?php trait database { use settings, session; private $pdo; // connect to database protected function connect() { try { $this->pdo = new PDO( "mysql:host=".$this->getSetting("db", "host").";dbname=".$this->getSetting("db", "database"), $this->getSetting("db", "user"), $this->getSetting("db","password") ); $this->init(); } catch (PDOException $e) { throw new Exception($e->getMessage()); } } } users.php <?php class users { use database; public function __construct() { try { $this->connect(); } catch (Exception $e) { throw new Exception($e->getMessage()); } } public function __destruct() { unset($this); } public function isAdmin() { try { if ($this->loginStatus() === true) { } else return false; } catch (Exception $e) { throw new Exception($e->getMessage()); } } public function loginStatus() { if (!$this->getSession("tysus") || !$this->getSession("tyspw")) // user is not logged in because we couldn't find session with username and/or password return false; if (!$this->userExists($this->getSession("tysus"), $this->getSession("tyspw"))) // user is unknown to database return false; // other checks failed, user must be logged in return true; } } 现在我收到此错误: 致命错误:在第 18 行 /home/deb2371/domains/nonamenohistory.com/public_html/include/classes/class.database.php 中调用未定义的方法 users::readSetting() 我以为会发生这样的事情: 类 users 使用 database 特征,并且该特征将使用 settings 和 session 特征。 如果是这样的话,我就不会收到任何错误,但不幸的是,事实并非如此。 有人知道如何解决这个问题吗? 代码重用是面向对象编程最重要的方面之一。 一个简单的Multiple Traits和Composing Multiple Traits示例,您可以通过它轻松分析您的情况。 使用多个特征 一个类可以使用多个特征。以下示例演示了如何在 IDE 类中使用多个特征。为了演示,它在 PHP 中模拟了 C 编译模型。 <?php trait Preprocessor{ function preprocess() { echo 'Preprocess...done'. '<br/>'; } } trait Compiler{ function compile() { echo 'Compile code... done'. '<br/>'; } } trait Assembler{ function createObjCode() { echo 'Create the object code files... done.' . '<br/>'; } } trait Linker{ function createExec(){ echo 'Create the executable file...done' . '<br/>'; } } class IDE{ use Preprocessor, Compiler, Assembler, Linker; function run() { $this->preprocess(); $this->compile(); $this->createObjCode(); $this->createExec(); echo 'Execute the file...done' . '<br/>'; } } $ide = new IDE(); $ide->run(); 组合多个特征 通过在特征声明中使用 use 语句,特征可以由其他特征组成。请参阅以下示例: <?php trait Reader{ public function read($source){ echo sprintf("Read from %s <br/>",$source); } } trait Writer{ public function write($destination){ echo sprintf("Write to %s <br/>",$destination); } } trait Copier{ use Reader, Writer; public function copy($source,$destination){ $this->read($source); $this->write($destination); } } class FileUtil{ use Copier; public function copyFile($source,$destination){ $this->copy($source, $destination); } } 您的问题可能是由于您使用了 readSetting 但它实际上被称为 getSetting

回答 2 投票 0

定义与变量a相同类型的变量b

是否可以声明一个与另一个变量 var_a 类型相同的变量 var_b? 例如: 模板 无效 foo(T t) { 自动 var_a = 条(t); //使 var_b 相同...

回答 3 投票 0

PHP 多个特征中的同名魔术方法

相同魔法方法的特性冲突如何解决? 特征和扩展类中的所有 __get 方法都应该可用。理想情况下,我希望 Foo::__get 优先于...

回答 1 投票 0

收集不同引脚和计时器的特征

我使用 avr-hal 来控制 arduino uno 上数字输出上 LED 的 RGB,并使用 set_duty 进行各种 TimerPWM 和 PD 来更改颜色。因为这工作正常并且具有

回答 1 投票 0

这是什么:`impl<T: Default> T {} 的特征`?

最近我看到不同的地方将其作为示例代码给出,并在我的编辑器中编写它,它似乎是有效的代码。 特质 特质 {} impl T {} 的特征 我好像没找到

回答 1 投票 0

这是什么:`impl<T> T {}`?

最近我看到不同的地方将其作为示例代码给出,并在我的编辑器中编写它,它似乎是有效的代码。 特质 特质 {} impl T {} 的特征 我好像没找到

回答 1 投票 0

这是什么:`impl<T> T {} 的特征`?

最近我看到不同的地方将其作为示例代码给出,并在我的编辑器中编写它,它似乎是有效的代码。 特质 特质 {} impl T {} 的特征 我好像没找到

回答 1 投票 0

在自定义结构上实现 actix_web::Responder 特征

我正在使用 actix-web v4。 我正在尝试实现一个具有自定义结构的 Web 服务来处理错误: pub 结构 ApiError { 发布消息:字符串, 发布代码:ErrorEnum, 酒吧详情:V...

回答 1 投票 0

为相同特征的特征对象使用 move 方法来实现特征

根据下面的内容,我试图在具有相同特征的盒装特征对象上实现一个特征。我之前已经为特质做过这件事,其方法采用 &self ,效果很好,但不是 self。 // 紫色...

回答 1 投票 0

对派生的 `Eq`、`Ord` 等实现的自动生成特征约束

我对 Ord 和类似特征的派生实现生成的约束有点困惑。 我注意到,不可能为包含 Phantom 的结构派生 Ord...

回答 1 投票 0

Rust:对派生的 `Eq`、`Ord` 等实现自动生成的 Trait 约束

我对 Ord 和类似特征的派生实现生成的约束有点困惑。 我注意到,不可能为包含 Phantom 的结构派生 Ord...

回答 1 投票 0

为什么我必须为一种类型而不是另一种类型指定 Into 实现?

我有这两个结构 #[导出(复制、克隆、调试、Eq、PartialEq)] pub 结构 Vin { 数据:[u8; 17], } 实现 Vin { pub fn new(数据: [u8; 17]) -> Vin { Vin {数据} } } 暗示...

回答 1 投票 0

在 Rust 中实现模板方法设计模式

这实际上来自另一个案例,但这里进行了简化。假设我们想要实现模板方法设计模式并提供一个包含主要算法实现的库,并且

回答 1 投票 0

© www.soinside.com 2019 - 2024. All rights reserved.