【问题标题】:How to write out a non-literal string?如何写出非文字字符串?
【发布时间】:2014-05-05 16:54:02
【问题描述】:

如何写出s的内容?

let file = File::create(&Path::new("foo.txt"));

let s = "foo";

file.write(bytes!(s));   // error: non-literal in bytes!

谢谢。

【问题讨论】:

    标签: string io rust


    【解决方案1】:

    使用write_str:

    let mut file = File::create(&Path::new("foo.txt"));
    
    let s = "foo";
    
    file.write_str(s);
    

    【讨论】:

    • 谢谢,这行得通!然而,我似乎在分解我的问题时过于简单化了,因为我希望答案能符合我的真正目标。本质上,我正在尝试使用write(bytes!(concat!(s, "bar"))); 连接字符串和非文字字符串 - 但编译器需要文字。有什么线索吗?谢谢。
    • @user3596561 暂时忘记concat! 的存在。你可能很长一段时间都不需要它。连接字符串通过std::strstd::strbuf 发生,可能s.append("bar") 用于一次性连接。
    • @delnan 魔法!以为我已经尝试了这个的各种排列并且只是在兜圈子 - 仍然试图了解 rust 的类型系统以及什么可以和不能去哪里。慢慢来……再次感谢。
    【解决方案2】:
    use std::io::File;
    
    fn main() {
        let mut file = File::create(&Path::new("foo.txt"));
    
        let literal = "foo";
        let string = "bar".to_owned();
    
        file.write_str(literal);
        file.write_str(string.as_slice());
    }
    

    as_slice 返回一个字符串切片,即。 &str。与字符串字面量相关的变量也是一个字符串切片,但引用具有静态生命周期,即。 &'static str.

    如果您可以轻松地分别编写文字和字符串,以上就是您会做的事情。如果需要更复杂的东西,这将起作用:

        //Let's pretend we got a and b from user input
        let a = "Bob".to_owned();
        let b = "Sue".to_owned();
        let complex = format!("{0}, this is {1}. {1}, this is {0}.", a, b);
        file.write_str(complex.as_slice());
    

    【讨论】:

      猜你喜欢
      • 2011-11-14
      • 2017-12-10
      • 2011-08-10
      • 2011-02-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多