Reputation: 11
I want to be able to write code like this:
ExampleStruct {
field1: "value1",
field2: "value2",
nested: ExampleNestedStruct{
field3: "value3",
},
}
for a struct that looks like this:
struct ExampleStruct{
field1: String,
field2: String,
nested: ExampleNestedStruct
}
struct ExampleNestedStruct {
field3: String,
}
but since ExampleStruct has to have fields of type String and not of type &str I'd have to convert every value explicitly with .to_owned() or similar fuctions, which works but isn't optimal.
I thought about creating an identical struct with &str fields and a conversion method utilizing serialization but that seems overcomplicated for such a simple issue, as well as having two essentially idential structs in my code.
Is there any way for me to convert all occuring &str to String implicitly? Or is there some syntax I might not know about? I'm quite new to rust over all.
I tried looking up possible Syntax of creating Strings which all seem to include some kind of explicit function call.
I also discovered some auto conversion syntax (if you can call it that) for function arguments like so: fn fn_name <T: Into<T'>> (s: T) but that won't work because I'm not calling a function with arguments.
Edit: I think I might be able to achieve this by writing a macro. I'll try that when I have time, unless theres someone out there who already created a &str_to_String macro perhaps?
Upvotes: 0
Views: 963
Reputation: 11
Alright, I managed to solve it by creating a macro for that. You can find it here https://crates.io/crates/append_to_string
Might look intimidating to some but it is not too complicated once you get familiar with the syn crate.
The macro now allows me to write my code like this:
// nested struct example
let b1 = append_to_string!(
B {
s1: "hello",
s2: "world",
a: A {
s1: "nested",
s2: "struct",
}
}
);
Instead of this:
let b2 = B {
s1: "hello".to_string(),
s2: "world".to_string(),
a: A {
s1: "nested".to_string(),
s2: "struct".to_string(),
}
};
Upvotes: 0
Reputation: 999
You should be able to use core::convert::Into trait. This is the code that you probably asking:
struct ExampleStruct {
field1: String,
field2: String,
nested: ExampleNestedStruct,
}
struct ExampleNestedStruct {
field3: String,
}
let e = ExampleStruct{
field1: "123".into(),
field2: "123".into(),
nested: ExampleNestedStruct {
field3:"123".into()
},
};
More details about the trait: https://doc.rust-lang.org/beta/core/convert/trait.Into.html
Upvotes: 2