How can I make part of a const
string conditional on some flag?
#[cfg(target_os = "macos")]
const OS: &'static str = "OSx";
#[cfg(target_os = "windows")]
const OS: &'static str = "Windows";
const SOME_STRING: &'static str = format!("this os is {}", OS);
This code doesn't compile because the format
macro returns a String
. I'd like to be able to do this formatting without any allocation. Is it possible to do without making the whole string conditional?
The java string format () method returns the formatted string by given locale, format and arguments. If you don't specify the locale in String.format () method, it uses default locale by calling Locale.getDefault () method. The format () method of java language is like sprintf () function in c language and printf () method of java language.
String formatting is the process of inserting variables into a string. In modern languages generally, it is done by using the {} brackets. It is also called string interpolation. Many languages have a built-in string method to format strings, but not all languages have it. Another very famous approach to string formatting is concatenation.
We can use the format () function in C++20 to format strings. To use the format () function, we must include the following library: template< class... T > template< class... T > param: The strings being formatted. format: The format string to format param.
Whitespaces include spaces, tabs, break lines, and so on. There are a couple of more ways you can format or modify strings in JavaScript. In this article, I've shared four of the most common methods you can use: toUpperCase, toLowerCase, replace and trim.
Well, for one, you should be aware of http://doc.rust-lang.org/stable/std/env/consts/constant.OS.html
Second, you can't really do this, exactly. You could use the lazy_static
crate, but that's still going to end up giving you an allocation.
In the future, when const fn
is stable, this should be easier to do.
You can use the const_format crate to do this.
use const_format::formatcp;
#[cfg(target_os = "macos")]
const OS: &'static str = "OSx";
#[cfg(target_os = "windows")]
const OS: &'static str = "Windows";
const SOME_STRING: &'static str = formatcp!("this os is {}", OS);
pub fn main() {
println!("{}", SOME_STRING);
}
this os is Windows
(This code is just for example as you could simply copy "this os is"
into each of the cfg strings, and also should consider using std::env::const::OS
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With