使用字符串键从结构中获取数据,并将结构转换为数组

Get Data From Structs With String Key, And Struct to Array

是否可以使用字符串键从结构中获取值? 像这样:

struct Messages {
    greetings: String,
    goodbyes: String
}

impl Structure {
    fn new() -> Structure{
        Messages {
            greetings: String::from("Hello world"),
            goodbyes: String::from("Bye!")
    }
}

fn main() {
    let messages = Messages::new();
    // now how do I print it out with a string key?
    println!("{}",messages["greetings"]); // prints "Hello world"

    // and can I even turn a struct into an array? Function name is made up
    let arr = Struct::to_array(messages);
}

请帮助thz

简而言之,不,这是不可能的。您的字段名称在运行时不一定可用以执行此类检查。但是,还有其他方法可以达到类似的效果:

  • 使用 HashMap<String, String>
  • 写一个函数来做:
impl MyStruct {
  pub fn get_field(&self, key: String) -> &str {
    if key == 'field1' {
      self.field1
    } else if ...
  }
}

或者换个方式解决

这种模式在 Rust 中没有得到很好的支持,尤其是与 JavaScript 这样的动态语言相比。许多 Rust 新手面临的一个问题是“以 Rust 方式”解决问题。

你的评论不是 100% 清楚,但听起来你的结构代表了一个井字棋盘,看起来像这样:

struct Board {
  top_right: String,
  top_middle: String,
  top_left: String,
  // etc...
}

虽然这行得通,但还有更好的方法可以做到这一点。例如,您可以用 enum 而不是 String 来表示每个图块,您还可以使用 Vec(类似于其他语言的 arrays/lists)来存储它数据:

enum Tile {
  Empty,
  Cross,
  Circle,
}

struct Board {
  tiles: Vec<Tile>,
}

impl Board {
  pub fn print(&self) {
    for tile in self.tiles {
      println!("{}", match tile {
        Tile::Empty => " ",        
        Tile::Cross => "X"
        Tile::Circle => "O",
      });  
    }
  }
}