简体   繁体   English

从 Rust 中的通用结构内部调用 T::new()

[英]Calling T::new() from inside generic struct in Rust

Halp.哈尔普。 Im a rust newbie and ive battled through a bunch of stuff over the last few days but cannot find any information about this.我是 rust 新手,过去几天我经历了很多事情,但找不到任何有关此的信息。 I have a generic struct (which i have simplified down to illustrate the issue): I want to be able to create a struct that does a bunch of stuff with a std::collections:,HashMap, HashSet.我有一个通用结构(我已经简化以说明问题):我希望能够创建一个结构,它可以使用 std::collections:,HashMap, HashSet 来做一堆事情。 List etc Im assuming i need to imply that T must implement a new method.?列出等 我假设我需要暗示 T 必须实现一个新方法。? using a trait?使用特征? or similar but searches just turn up basic stuff或类似的,但搜索只会出现基本的东西

public struct dude< T > {
    data : std::sync::Arc< T >,
}

impl < T > dude< T > {
    pub fn new() -> dude< T > {
        Reloader{ data : Arc::new( <T>::new() ) }
    }
}

Produces the following error:产生以下错误:

<T>::new();
     ^^^ function or associated item not found in `T`

When you use functions on a generic in rust, you need to specify a trait bound that proivdes those functions.当您在 rust 中的泛型上使用函数时,您需要指定提供这些函数的特征绑定。

For example what if I tried to call Dude::new() with a class that doesn't provide a new function?例如,如果我尝试使用不提供new function 的 class 调用Dude::new()怎么办? In some languages (like C++) this would be flagged as an error where you tried to actually create the instance - but in rust, there is a principle of locality of reasoning.在某些语言(如 C++)中,这将被标记为您尝试实际创建实例的错误 - 但在 rust 中,存在推理的局部性原则。

There is an existing trait that provides functionality like new() - Default - which provides Default::default() using that as a trait bound looks like this:有一个现有的 trait 提供了new() - Default之类的功能,它提供Default::default()使用它作为 trait 绑定,如下所示:

use std::sync::Arc;
pub struct Dude<T> {
    data : std::sync::Arc<T>,
}

impl<T:Default> Dude<T> {
    pub fn new() -> Dude<T> {
        Dude{ data : Arc::new( Default::default() ) }
    }
}

The Default trait is implemented already for many types, for any custom types you can easily derive it (and clippy even gives you a warning about not implementing it im many places). Default trait 已经为许多类型实现了,对于任何自定义类型,您都可以轻松地派生它(并且 clippy 甚至会警告您在很多地方都没有实现它)。

Now I can write:现在我可以写:

let dude: Dude<String> = Dude::new();

It probably makes sense implement this for Dude too, rather than provide new inside Dude itself.Dude实现这一点可能也很有意义,而不是在Dude本身内部提供新的。

impl<T:Default> Default for Dude<T> {
  fn default() -> Dude<T> {
    Dude{ data : Arc::new( Default::default() ) }
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM