Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format a const string

Tags:

rust

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?

like image 917
awelkie Avatar asked Aug 28 '15 21:08

awelkie


People also ask

How to use string format () method in Java?

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.

What is string formatting in programming?

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.

How to format strings in c++20 with format() function?

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.

How do I format a string in JavaScript?

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.


2 Answers

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.

like image 186
Steve Klabnik Avatar answered Sep 21 '22 04:09

Steve Klabnik


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)

like image 24
Mingwei Samuel Avatar answered Sep 20 '22 04:09

Mingwei Samuel