#How to safely get string literal from String

29 messages · Page 1 of 1 (latest)

candid lagoon
#

I want to format a string loaded in from a file

error: format argument must be a string literal
--> src/main.rs:22:31
|
22 | let config_html = format!(config_html_skeleton, String::from("data:application/octet-stream;charset=utf-8;base64,") + &encod...
| ^^^^^^^^^^^^^^^^^^^^
|
help: you might be missing a string literal to format with
|
22 | let config_html = format!("{} {}", config_html_skeleton, String::from("data:application/octet-stream;charset=utf-8;base64,") + &encode(configfile));
| ++++++++

error: argument must be a string literal
--> src/main.rs:23:27
|
23 | println!(include_str!(config_html_skeleton));
| ^^^^^^^^

let config_html_skeleton = include_str!("../config-button.html");
let config_html = format!(config_html_skeleton, String::from("data:application/octet-stream;charset=utf-8;base64,") + &encode(configfile));
println!(include_str!(config_html_skeleton));
limber egret
#

Maybe include_str!() help

#

Or custom proc_macro

#

There is no way to get a literal at runtime from file, just because literal is part of syntax, not a value category

#

Also, iirc, there is a format method present in stdlib, which does the same, but without static verification

candid lagoon
#

gotcha Ill have a look for that

steep coral
#

Also for your println thing, you just need to put it in the args:

println!("{}", config_html_skeleton);
candid lagoon
#

when I try that it ends up wanting more if that makes sense?
ill post error

neverming misread my error from before

limber egret
#

Ah, sorry, you tried include_str, I didn't see at first time

willow aurora
#

why not println!("{}",include_str!(config_html_skeleton)); ?

steep coral
#

You can't include_str runtime values

candid lagoon
#

hmm so if i pass include_str in arguments it stays on the stack and I dont need to worry about memory leaks?

steep coral
#

Nothing about this concerns the stack or memory leaks.

candid lagoon
#

gotcha

limber egret
verbal mist
limber egret
#

Hm, looks like that will not work... Its only to back format!()...

verbal mist
#

Also: if you put include_str! directly in the println!/format! invocation, it will work

steep coral
#

no it didn't

candid lagoon
#

but its printing on my console

verbal mist
#
$ cat a.rs
fn main() {
    println!(include_str!("hello.txt"), "world");
}
$ cat hello.txt 
Hello, {}!
$ rustc a.rs && ./a
Hello, world!
verbal mist
candid lagoon
#

let config_html = format!(include_str!("../config-button.html"), String::from("data:application/octet-stream;charset=utf-8;base64,") + &encode(configfile));
println!("{}", config_html);

steep coral
limber egret
#

You just use include_str improperly. it doesn't transform variable to literal - it just loads file contents at compile time

steep coral
verbal mist
steep coral
#

Normally this wouldn't matter much, but you're copying an entire base64-encoded thing so I'm mentioning it.