This question already has answers here:
How to convert a String into a &'static str
(4 answers)
How can you make a safe static singleton in Rust?
(3 answers)
How do I create a global, mutable singleton?
(7 answers)
Closed 3 years ago.
I have the following function:
fn load_data() -> Result<MyData> {
// ...
Ok(my_data)
}
I want to call this function only once during the execution of my program and save the result in a static variable.
It'd be nice if the result is of type Option<MyData>, so the consumer just needs to check if the data is there or not, regardless of the reason of why it's not there.
I have came up with the following:
lazy_static! {
static ref DATA: Option<&'static MyData> = load_data().ok().as_ref();
}
However, that line fails:
35 | static ref DATA: Option<&'static MyData> = load_data().ok().as_ref();
| ----------------^^^^^^^^^
| | returns a value referencing data owned by the current function
| |
| |
| temporary value created here
Is there a way to achieve what I want or am I conceptually wrong?
Related
This question already has answers here:
How do I return a reference to something inside a RefCell without breaking encapsulation?
(3 answers)
How to borrow the T from a RefCell<T> as a reference?
(1 answer)
How can I obtain an &A reference from a Rc<RefCell<A>>?
(1 answer)
Closed 7 months ago.
I am trying to make a rust program that can parse equations. One part of the program requires, that I have multiple variable objects that point to a single definition. To be able to do that I use a VariableContext object that stores multiple variable definitions. It has a get_variable method that either returns a new variable or an existing one. This object is then passed to a parser function. Sadly I seem unable to actually use the returned variable, I have already tried wrapping the VariableContext object in a Rc, but it still gives me errors.
The parse function:
fn parse<'a>(
tokens: Vec<Token<'a>>
context: Rc<RefCell<VariableContext<'a>>>,
) -> Result<ExprVariant<'a>, ParserError> {
/* ... */
let variable = (*context).borrow_mut().get_variable(token.slice);
Ok(expression::ExprVariant::Variable(variable))
/* ... */
}
the VariableContext struct:
pub struct VariableContext<'a>{
pub variables: Vec<Rc<VariableDefinition<'a>>>
}
The get_variable method:
pub fn get_variable(&'a mut self, name: &str) -> VariableExpr<'a> {
if let Some(definition) = self.find_definition(name){
let variable = VariableExpr::new(definition.clone());
variable
//ExprVariant::Variable(variable)
}else{
let definition = Rc::new(VariableDefinition::new(name.to_string()));
self.add_definition(definition.clone());
let variable = VariableExpr::new(definition.clone());
//ExprVariant::Variable(variable)
variable
//&self.variables[self.variables.len()-1]
}
}
The Error:
error[E0515]: cannot return value referencing function parameter `context`
--> src/parser/textparser.rs:35:13
|
34 | let variable = (*context).borrow_mut().get_variable(token.slice);
| ------- `context` is borrowed here
35 | Ok(expression::ExprVariant::Variable(variable))
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ returns a value referencing data owned by the current function
I am sorry if I haven't given enough information or am doing something stupid
This question already has answers here:
Return local String as a slice (&str)
(7 answers)
Proper way to return a new string in Rust
(2 answers)
What does “`str` does not have a constant size known at compile-time” mean, and what's the simplest way to fix it?
(1 answer)
What are the differences between Rust's `String` and `str`?
(14 answers)
Closed 1 year ago.
If I do
fn split(text: String) -> Vec<str> {
It tells me this
29 | fn split(text: String) -> Vec<str> {
| ^^^^^^^^ doesn't have a size known at compile-time
|
= help: the trait `Sized` is not implemented for `str`
100% not the best way to do this but I did this
fn split(text: String) -> Vec<String> {
let mut output_string:Vec<String> = Vec::new();
for x in output {
output_string.push(String::from(x));
}
return output_string;
This question already has answers here:
Convert Vec<String> into a slice of &str in Rust?
(2 answers)
How do I get a slice of a Vec<T> in Rust?
(2 answers)
borrowed value does not live long enough in loop
(2 answers)
Closed 2 years ago.
There's an object that only accepts &[&str] as input, but I need to generate this list dynamically. I tried many ways but I always get errors.
My code:
use std::fs;
fn example() {
let paths = fs::read_dir("./").unwrap();
let mut input_files = Vec::<&str>::new();
for path in paths {
let x = ["../", path.unwrap().path().to_str().unwrap()]
.concat()
.as_str();
input_files.push(x);
}
}
Error:
error[E0716]: temporary value dropped while borrowed
--> src/lib.rs:8:17
|
8 | let x = ["../", path.unwrap().path().to_str().unwrap()]
| _________________^
9 | | .concat()
| |_____________________^ creates a temporary which is freed while still in use
10 | .as_str();
| - temporary value is freed at the end of this statement
11 | input_files.push(x);
| - borrow later used here
|
= note: consider using a `let` binding to create a longer lived value
I think the error is because concat creates a temporary, but why? Why can it not return a string and how should I fix this?
I can't use String.
This question already has answers here:
How to solve "returns a value referencing data owned by the current function" error in Rust? [duplicate]
(1 answer)
Return local String as a slice (&str)
(7 answers)
Why can't I return an &str value generated from a String?
(1 answer)
Is there any way to return a reference to a variable created in a function?
(5 answers)
Closed 3 years ago.
For the following code:
fn get_lines() -> String {
String::from("Hello\nWorld")
}
fn get_first_line(s: &String) -> &str {
s.lines().next().unwrap()
}
struct World<'a> {
a_str: &'a str,
}
fn work<'a>() -> World<'a> {
let s1 = get_lines();
let s2 = get_first_line(&s1);
World { a_str: s2 }
}
fn main() {
let w = work();
}
I got the following error:
error[E0515]: cannot return value referencing local variable `s1`
--> src/main.rs:17:5
|
15 | let s2 = get_first_line(&s1);
| --- `s1` is borrowed here
16 |
17 | World { a_str: s2 }
| ^^^^^^^^^^^^^^^^^^^ returns a value referencing data owned by the current function
How to build a struct instance using s2? Is it a conceptual error of the World struct?
World refers to a str slice which must be owned by something else. Your function work allocates a new String (through get_lines), and makes a reference into it (through get_first_line). When it returns, the String goes out of scope and will be dropped, so you cannot keep a reference to it, since the thing it refers to is no longer there.
If you want a World object that does not depend on a String owned by something else, it will need to own the data itself: Contain a String instead of a &'a str.
See also 'dangling references' in the Rust Book.
This question already has answers here:
Is there any way to return a reference to a variable created in a function?
(5 answers)
Return local String as a slice (&str)
(7 answers)
Proper way to return a new string in Rust
(2 answers)
Closed 4 years ago.
I have a struct that contains references to two different values. There's two constructors - one that takes a reference for each value, and one that only takes a reference to one of the values while assigning a default to the other.
My problem is assigning that default. See the code below:
struct Foo<'t> {
a: &'t String,
b: &'t String,
}
impl<'t> Foo<'t> {
fn new(a: &'t String, b: &'t String) -> Foo<'t> {
Foo { a, b }
}
fn new_with_default_b(a: &'t String) -> Foo<'t> {
Foo {
a,
b: &String::from("default"),
}
}
}
This does not compile:
error[E0515]: cannot return value referencing temporary value
--> src/lib.rs:12:9
|
12 | / Foo {
13 | | a,
14 | | b: &String::from("default"),
| | ----------------------- temporary value created here
15 | | }
| |_________^ returns a value referencing data owned by the current function
Is it possible to fix this?