Table of content

What is this :grey_question:

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 :white_check_mark:

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.

	// Boilerplate for my singleton example
	struct A;
	static THING: A = A {};
	fn getInstance() -> &'static A {
	    &THING
	}

	fn main() {
	    {
	        // The following two lines are identical
	        // due to static lifetime elision both
	        // variables have a 'static lifetime
	        const X1: &str = "a";
	        const X2: &'static str = "a";

	        // The following three lines are identical
	        // X1 and X2 are replaced with the strings at
	        // compile time
	        let a = X1;
	        let b = X1;
	        let c = X2;

	        assert_eq!(b.as_ptr(), a.as_ptr());
	        assert_eq!(b.as_ptr(), c.as_ptr());
	        // When  these constants go out of scope, their references
	        // can no longer be used, but the data remains in the binary.
	    }

	    {
	        // Two ways to make a constant with `'static` lifetime.
	        let X1: &'static str = "a";
	        static X2: &str = "a";

	        // The following will add three references
	        // non mutable borrows to X1
	        let a = X1;
	        let b = X1;
	        let c = X2;

	        assert_eq!(b.as_ptr(), a.as_ptr());
	        assert_eq!(b.as_ptr(), c.as_ptr());
	        // When  these constants go out of scope, their references
	        // can no longer be used, but the data remains in the binary.
	    }

	    {
	        // Implementing the singleton pattern
	        let _a = getInstance();
	        let _b = getInstance();
	    }
	
	

github playground

See also thestackoverflow thread on the topic.