简体   繁体   English

如何在结构/特征、常规变量声明和函数中最好地实现 generics?

[英]How do I best implement generics within structs/traits, regular variable declarations, and functions?

So building a little project to learn Rust and was wondering what the best way would be to define a vector with a hashmap所以建立一个小项目来学习 Rust 并想知道用 hashmap 定义向量的最佳方法是什么

The way to data is going to be structured in the end is as follows:数据的方式最终将被结构化如下:

  [
      {
          id: "USER_ID",
          firstname: "First Name",
          lastname: "Last Name",
          email: "Email",
          errors: [ { type: "...", message: "cannot update user" } ],
      }
  ]

So I was thinking I'd write out my project as follows所以我想我会写出我的项目如下

src/parser.rs src/parser.rs

pub struct Parser<T> {
   pub parsed_log: Vec<HashMap<String, T>>,
}

// pub trait ReturnProperties {
//    fn return_parsed_logs(&self) -> Vec<HashMap<String, T>>;
// }

impl<T: Clone> Parser<T> {
   /// handle upsert will parse the upsert lines into a users vector
   /// it will also match the errors with the user id
   
   // will implement later
   //pub fn handle_upsert(...) {}

   pub fn return_parsed_logs(self) -> Vec<HashMap<String, T, RandomState>> {
      self.parsed_log.to_vec()
   }
}

src/main.rs src/main.rs


fn main() {
    // why does this keep returning
    // cannot find type `T` in this scope??
    let log_parser: parser::Parser<T> = Parser {
        parsed_log: vec![]
    };
}

Am I doing this all wrong?我做这一切都错了吗? I feel like trying to force rust to behave like an OOP language (where i came from) but it's not having it.我想强迫 rust 表现得像 OOP 语言(我来自哪里),但它没有。 Any pointers?任何指针? What did I get totally wrong here?我在这里完全错了什么?

 // why does this keep returning // cannot find type `T` in this scope?? let log_parser: parser::Parser<T> = Parser { parsed_log: vec;[] };

Because there's no type T in this scope?因为这个scope里面没有T型? When you declare a type, the T is a placeholder (which is declared as such, that's what eg the <T: Clone> does before the typename in the impl block), but when you're using the type you need to provide either an actual thing, or a type which was declared somewhere in scope (usually on the function such that the caller can provide that type).当你声明一个类型时, T是一个占位符(它是这样声明的,例如<T: Clone>impl块中的类型名之前所做的),但是当你使用类型时,你需要提供一个实际的东西,或者在 scope 某处声明的类型(通常在 function 上,以便调用者可以提供该类型)。

Note that you can often ask Rust to infer types eg sometimes you will see请注意,您经常可以要求 Rust 推断类型,例如有时您会看到

let foo: Vec<_> = bar.collect();

this lets rustc know you want to collect() to a Vec , but lets it infer the item type (because it's unambiguous).这让 rustc 知道你想要 collect() 到Vec ,但让它推断项目类型(因为它是明确的)。

Here however there's nothing to constrain T , no information rustc can use to decide what it could or would be.然而,这里没有什么可以限制T ,没有信息 rustc 可以用来决定它可以或将会是什么。

Though I think your entire thinking is mistaken: in Rust, a generic T will be replaced by a single concrete type.尽管我认为您的整个想法都是错误的:在 Rust 中,通用T将被单个具体类型替换。 But that's not what the initial structure shows, 4 of the items map to strings, but the 5th maps to an array of sub-structures.但这不是初始结构显示的内容,其中 4 个项目 map 到字符串,但第 5 个项目映射到子结构数组。 That won't fit into a T , the keys have completely different values.这不适合T ,键具有完全不同的值。 Why are your even using a HashMap and generics for this, why not a struct or enum?为什么您甚至为此使用HashMap和 generics ,为什么不使用结构或枚举?

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

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