5

I want to have a const or static which is a random number appended by a dot. In Java it produces what I want, but in Rust I get variety of errors

const SOME_STR:  &'static str = format!("{}.", rand::random::<u64> ()).as_str();

static SOME_STR:  &'static str = format!("{}.", rand::random::<u64> ()).as_str();

I get errors like

  1. calls in statics are limited to struct and enum constructors
  2. static contains unimplemented expression type
  3. borrowed value does not live long enough

What are my options here and what is an easy way to fix this?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
misnomer___
  • 355
  • 1
  • 3
  • 8
  • [How can you make a safe static singleton in Rust?](https://stackoverflow.com/q/27221504/3650362) has an example of using the `lazy_static` crate for a similar use case. [Here's an application of the same strategy to your problem.](https://play.rust-lang.org/?gist=ec5d8b67727c2d8cc569dc563fdf2661&version=stable&mode=debug) – trent May 31 '18 at 02:40
  • Thanks a lot. I want to follow up on a basic question Why cant I do static ref PREFIX: &'static str = format!("{}.", rand::random::()).as_str(); in a single line. Why should I take an extra pointer? – misnomer___ May 31 '18 at 19:49
  • `format!` returns a `String`, which would be dropped if you called `.as_str()` on it without saving it somewhere. With `lazy_static!` only the final value of the initializer expression is saved and leaked. You could instead write what `lazy_static!` does manually, and leak the `String` directly, but at best you're saving a couple bytes. – trent May 31 '18 at 20:21
  • If you don't want to expose the `String` to your public API, you could split the `lazy_static!` into a public part and a private part in a non-public module. [Example](https://play.rust-lang.org/?gist=46e261333adacdcc130ab91a4899260d&version=stable&mode=debug) – trent May 31 '18 at 20:24

0 Answers0