#How to store &str dynamically when program is running
11 messages · Page 1 of 1 (latest)
Post the error from cargo check please, not a picture
error[E0277]: the size for values of type `str` cannot be known at compilation time
--> src/item.rs:59:64
|
59 | result = format!("\"{}\": {:?}", self.name, self.value.downcast_ref::<str>());//.expect("111").to_string());
| ^^^^^^^^^^^^ doesn't have a size known at compile-time
what about this?
thank ypu
hi again, your variant is always return None
?play ```rust
use core::any::Any;
pub fn print_if_str(s: Box<dyn Any>) {
if let Some(s) = s.downcast_ref::<&str>() {
println!("It's a str({}): '{}'", s.len(), s);
} else {
println!("Not a str...");
}
}
fn main() {
print_if_str(Box::new("cookie monster"));
}```
Running `target/debug/playground`
It's a str(14): 'cookie monster'
18 pub struct Item {
17 ▏ parent: Parent,
16 ▏ value: Box<dyn Any>,
▎ 15 ▏ name: &'static str,
14 }
13
12 impl Item {
▎ 11 ▏ pub fn new<T: 'static>(parent: Parent, value: T, name: &'static str) -> Self {
10 ▏ ▏ Item { parent, value: Box::new(value), name }
9 ▏ }
8 ▏ pub fn print(&self) -> String {
▲ 7 ▏ ▏ let mut result = String::new();
▎ 6 ▏ ▏ result = format!("\"{}\": {:?}", self.name, self.value.downcast_ref::<&str>());//.expect
5 ▏ ▏ for _ in 0..self.parent.pr as i32 {
4 ▏ ▏ ▏ result = format!(" {}", result)
3 ▏ ▏ }
2 ▏ ▏ result
1 ▏ }
65 }
do you have an example that can run?