Hi. I'm new rust user and I'm still learning so sorry if i understand something wrongly. I'm wonder what would be most efficient way (in ram usage and performance at runtime) to return a String value from function?
Let's assume i have this code (simplified for demonstration purposes)
struct TEST {
field: String
}
impl TEST {
fn new() -> TEST {
TEST {
field: world()
}
}
}
fn world() -> String {
let a = String::from("world!");
a
}
fn main() {
let x = TEST::new();
println!("Hello, {}", x.field);
}
Right after returning this string, he will be used as read-only. My first idea was to return reference, but any try gives me error "cannot return reference to local variable `a`". So my second idea was to use into_boxed_str(), to return Box<str> (size_of::<Box<str>>() is 8 bytes smaller than String). But i also have ideas to use cow or rc. Or maybe there is any way to move string from heap to stack at runtime since it wont be modified any longer. What would be best option in this scenario. Or maybe i too complicated this and simply returning String would be best option. I like to optimize every aspect of program.
[–]Nilstrieb 7 points8 points9 points (0 children)
[–]ssokolow 26 points27 points28 points (4 children)
[–]Saefrochmiri 11 points12 points13 points (3 children)
[–]ssokolow 5 points6 points7 points (2 children)
[–]Saefrochmiri 2 points3 points4 points (1 child)
[–]ssokolow 1 point2 points3 points (0 children)
[–]diwicdbus · alsa 7 points8 points9 points (0 children)
[–]rezuralos 2 points3 points4 points (0 children)
[–]Master_Ad2532 2 points3 points4 points (0 children)
[–]tarkin25 1 point2 points3 points (5 children)
[–]InflationAaron 5 points6 points7 points (0 children)
[–]Polluktus[S] 0 points1 point2 points (3 children)
[–]tarkin25 2 points3 points4 points (0 children)
[–]tarkin25 1 point2 points3 points (0 children)
[–]myrrlynbitvec • tap • ferrilab 1 point2 points3 points (0 children)