返回文章列表

文章

Rust中的Option<i32>转字符串

目录
  1. 你可以用多种方式把 Option<i32> 转成 String,常见的有:
  2. 1. map_or / map_or_else
  3. 2. match
  4. 3. 先解包再 to_string
  5. 4. 用 format!
  6. 小结

你可以用多种方式把 Option<i32> 转成 String,常见的有:#

1. map_ormap_or_else#

let maybe_num: Option<i32> = Some(42);
let s: String = maybe_num
    .map_or("".to_string(), |v| v.to_string());
assert_eq!(s, "42");

let none_num: Option<i32> = None;
let t: String = none_num
    .map_or("".to_string(), |v| v.to_string());
assert_eq!(t, "");
  • 如果是 Some(v),就调用 v.to_string();否则返回 ""。 如果你想给 None 一个默认文本,比如 "N/A"
let s = maybe_num.map_or_else(|| "N/A".to_string(), |v| v.to_string());

2. match#

let maybe_num: Option<i32> = Some(7);
let s = match maybe_num {
    Some(v) => v.to_string(),
    None    => String::new(),  // 或者 "0".to_string(), "N/A".into() 等
};

3. 先解包再 to_string#

如果你已经想好了默认值:

let default = 0;
let num = maybe_num.unwrap_or(default);
let s = num.to_string();  // 不会是 None,因为你给了 unwrap_or

4. 用 format!#

let maybe_num: Option<i32> = Some(100);
let s = if let Some(v) = maybe_num {
    format!("{}", v)
} else {
    String::new()
};

小结#

  • 简洁推荐

let s = opt.map_or("".to_string(), |v| v.to_string()); ```

  • 可定制:把 "" 换成任何你希望的默认字符串。