我试图将结构存储在HashMap以字符串为键的结构中,以便以后可以通过字符串创建新对象。想想一个 REST API,客户端可以通过提供一个名称来让服务器实例化一个特定的对象。
use std::collections::HashMap;
struct MyStruct;
impl MyStruct {
pub fn new() -> Self {
Self {}
}
}
struct MyOtherStruct;
impl MyOtherStruct {
pub fn new() -> Self {
Self {}
}
}
fn main() {
let mut h = HashMap::new();
h.insert("MyStruct", MyStruct);
h.insert("MyOtherStruct", MyOtherStruct);
// This is pseudo-code
let obj = h.get("MyStruct").unwrap()::new();
}
Run Code Online (Sandbox Code Playgroud)
正如我所料,由于语法错误,这不起作用:
use std::collections::HashMap;
struct MyStruct;
impl MyStruct {
pub fn new() -> Self {
Self {}
}
}
struct MyOtherStruct;
impl MyOtherStruct …Run Code Online (Sandbox Code Playgroud) rust ×1