Rust challenge 43/100 - rust lifetimes - static life times v.s. constants
Table of content
What is this
The rules of the game are explained in my original post.
43rd Challenge
Challenge
Today I’m posting the first time this year. I had to take an unplanned break in the middle of AOC 2021. I plan to finish AOC 2021 and clean up my answers that are unfinished, but first I want to do some other things on other topics. Today’s challeng is to explore the concept of lifetimes
by example.
Today I want to answer the question, what is the difference between const X:&str = "0"
and let x: &'static str = "0"
?
Solution
The difference between constant const
and a variable is written in the documentation for the const
key word
constants are inlined wherever they’re used, making using them identical to simply replacing the name of the const with its value
oh the other hand ..
Static variables, on the other hand, point to a single location in memory, which all accesses share.
Also, static variables are variables and can be changes, constants cannot be changed at runtime.
To me it seems this would be useful when implementing a singleton pattern in rust. So I did just that bellow.
See also thestackoverflow thread on the topic.