3

从 toml 文件读取的字符串值包含额外的引号:

  # Toml file
  string_key = "fdsafdsafdsfds"

代码:

let cfg_file_content = get_config_file_content();
let cfg_data: Value = toml::from_str(&cfg_file_content).expect("failed to parse toml");
cfg_data.as_table().unwrap();

//1
let val1 = cfg_data.get("string_key").unwrap();

// ====> \""fdsafdsafdsfds\""
// or String("fdsafdsafdsfds")



//2
let val = format!("value is: {}", val1);
println!("{:?}", val);

// ====> "value is: \"fdsafdsafdsfds\""

如何删除这些额外的引号?

箱:

toml = "0.4.5"
4

1 回答 1

3

val1是toml的Value枚举,需要转换成str:

let val = format!("value is: {}", val1.as_str().unwrap());

但是,您应该使用可以为您完成工作的serde crate。

举个例子:

extern crate toml;
#[macro_use]
extern crate serde_derive;

#[derive(Serialize, Deserialize, Debug)]
struct Foo {
    string_key: String,
}

fn main() {
    let foo: Foo = toml::from_str("string_key = \"fdsafdsafdsfds\"").unwrap();
    println!("{:?}", foo);

    // or
    use std::collections::BTreeMap;
    let foo: BTreeMap<String, String> = toml::from_str("string_key = \"fdsafdsafdsfds\"").unwrap();
    println!("{:?}", foo);
}
于 2018-01-06T03:52:29.827 回答