String :: from(“”)在匹配臂中的何处分配?

时间:2019-06-17 06:32:48

标签: rust embedded

我仍然很陌生,来自C嵌入式世界。

如果我有一段这样的代码:

    match self {
        Command::AT => String::from("AT"),
        Command::GetManufacturerId => String::from("AT+CGMI"),
        Command::GetModelId => String::from("AT+CGMM"),
        Command::GetFWVersion => String::from("AT+CGMR"),
        Command::GetSerialNum => String::from("AT+CGSN"),
        Command::GetId => String::from("ATI9"),
        Command::SetGreetingText { ref enable, ref text } => {
          if *enable {
            if text.len() > 49 {
              // TODO: Error!
            }
            write!(buffer, "AT+CSGT={},{}", *enable as u8, text).unwrap();
          } else {
            write!(buffer, "AT+CSGT={}", *enable as u8).unwrap();
          }
          buffer
        },
        Command::GetGreetingText => String::from("AT+CSGT?"),
        Command::Store => String::from("AT&W0"),
        Command::ResetDefault => String::from("ATZ0"),
        Command::ResetFactory => String::from("AT+UFACTORY"),
        Command::SetDTR { ref value } => {
          write!(buffer, "AT&D{}", *value as u8).unwrap();
          buffer
        },
        Command::SetDSR { ref value } => {
          write!(buffer, "AT&S{}", *value as u8).unwrap();
          buffer
        },
        Command::SetEcho { ref enable } => {
          write!(buffer, "ATE{}", *enable as u8).unwrap();
          buffer
        },
        Command::GetEcho => String::from("ATE?"),
        Command::SetEscape { ref esc_char } => {
          write!(buffer, "ATS2={}", esc_char).unwrap();
          buffer
        },
        Command::GetEscape => String::from("ATS2?"),
        Command::SetTermination { ref line_term } => {
          write!(buffer, "ATS3={}", line_term).unwrap();
          buffer
        }    
    }

它在Rust中如何工作?所有这些匹配臂会立即求值,还是只有一个匹配臂在堆栈上创建可变的副本?而且,是否将String::from("")中的所有字符串文字分配到.rodata中?

有没有更好的方式来做我在这里要做的事情?本质上,我想返回带有替换参数(写!宏位)的字符串文字吗?

最诚挚的问候

1 个答案:

答案 0 :(得分:4)

仅匹配臂将被评估。不匹配的分支在程序大小上没有花费。

在一般情况下,甚至无法评估其他分支,因为它们取决于使用模式分解读取的数据。

关于第二个问题,在程序中存储文字的位置通常不命名为rodata,也没有指定或保证(通常是重复数据删除,但这只是优化)。