I have the following definitions
enum Score {
SEND,
}
enum ScoreAtom {
IntAtom(i64),
}
enum Node {
Leaf(ScoreAtom),
}
And I have a method return a constant value.
fn object_score(&mut self) -> Option<Node<'a>> {
Some(Node::Leaf(ScoreAtom::IntAtom(Score::SEND as i64)))
}
Because the source code is long, I can't paste everything here, you may find full source code at here.
When object_score is called, where is the return value allocated? Stack or Heap?
Its size is known at compile-time, but it escapes the function scope, I am afraid Rust compiler will let it allocate from heap. Is that right?
As everyone knows, allocation on heap is much heavier than stack, and it is not friendly to CPU caches.
If the answer to above question is heap, I intent to optimize this method because it is on a frequent execution path.
I suppose to have a global static value to be reused on every return as below.
static OBJECT_SCORE : Option<Node<'_>> = Some(Node::Leaf(ScoreAtom::IntAtom(Score::SEND as i64)));
fn object_score(&mut self) -> Option<Node<'a>> {
OBJECT_SCORE
}
But it fails with following error
error[E0308]: mismatched types --> model/src/ordering/sort_send.rs:91:9 | 91 | OBJECT_SCORE | ^^^^^^^^^^^^ lifetime mismatch | = note: expected enum `Option<ordering::Node<'a>>` found enum `Option<ordering::Node<'static>>` note: the lifetime `'a` as defined on the impl at 87:6... --> model/src/ordering/sort_send.rs:87:6 | 87 | impl<'a> SendScoreTreeIter<'a> { | ^^ = note: ...does not necessarily outlive the static lifetime
It is quite confusing, the static lifetime is certainly longer than any other lifetimes, why it rejects returning a 'static lifetime value? How can I fix it?
Sorry the full source code is too long to paste here. you may find them here.
Thank you in advance