Trying to declare a String const results in expected type, found “my string”

前端 未结 1 633
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-12 04:58

I\'m trying to declare a String constant in Rust, but I get a compiler error I just can\'t make sense of

const DATABASE : String::from(\"/var/li         


        
相关标签:
1条回答
  • 2021-01-12 05:22

    You should read The Rust Programming Language, second edition, specifically the chapter that discusses constants. The proper syntax for declaring a const is:

    const NAME: Type = value;
    

    In this case:

    const DATABASE: String = String::from("/var/lib/tracker/tracker.json");
    

    However, this won't work because allocating a string is not something that can be computed at compile time. That's what const means. You may want to use a string slice, specifically one with a static lifetime, which is implicit in consts and statics:

    const DATABASE: &str = "/var/lib/tracker/tracker.json";
    

    Functions that just need to read a string should accept a &str, so this is unlikely to cause any issues. It also has the nice benefit of requiring no allocation whatsoever, so it's pretty efficient.

    If you need a String, it's likely that you will need to mutate it. In that case, making it global would lead to threading issues. Instead, you should just allocate when you need it with String::from(DATABASE) and pass in the String.

    See also:

    • How to create a static string at compile time
    0 讨论(0)
提交回复
热议问题