How can I pass a variable initialized in main to a Rocket route handler?Need holistic explanation about Rust's cell and reference counted typesHow do I create a global, mutable singleton?Share i32 mutably between threadsCompiler says that data cannot be shared between threads safely even though the data is wrapped within a MutexHow to respond with a different value depending on the state of the Rocket server?Is there a faster/shorter way to initialize variables in a Rust struct?How to parse multipart forms using abonander/multipart with Rocket?Can I render a Template in Rocket with my own serialized struct?Can't return String from Rocket routeHow do I respond from a Rocket handler with content type application/hal+json?Rocket not parsing RawStr in a URL to match routeI want to start Rocket in a module out of `main()` but failedRocket port override from environment variable not working in WindowsIs there a way to create a central routing file which contains only routes and the functions they are for in Rocket?Access a variable that is inside an if statement

Obtaining the intermediate solutions in AMPL

Read file lines into shell line separated by space

Transposing from C to Cm?

Why do all fields in a QFT transform like *irreducible* representations of some group?

How can I unambiguously ask for a new user's "Display Name"?

How do I, an introvert, communicate to my friend and only colleague, an extrovert, that I want to spend my scheduled breaks without them?

Why is the UK so keen to remove the "backstop" when their leadership seems to think that no border will be needed in Northern Ireland?

Nothing like a good ol' game of ModTen

Numbers Decrease while Letters Increase

Improving Performance of an XY Monte Carlo

How do we calculate energy of food?

Do Bayesian credible intervals treat the estimated parameter as a random variable?

Prove your innocence

Round towards zero

How do the Etherealness and Banishment spells interact?

Why did Khan ask Admiral James T. Kirk about Project Genesis?

Another solution to create a set with two conditions

If someone uses the Command spell and says "drop", what happens?

How to respectfully refuse to assist co-workers with IT issues?

Non-visual Computers - thoughts?

Why doesn't 'd /= d' throw a division by zero exception?

Why is 1. d4 Nf6 2. c4 e6 3. Bg5 almost never played?

moon structure ownership

Could George I (of Great Britain) speak English?



How can I pass a variable initialized in main to a Rocket route handler?


Need holistic explanation about Rust's cell and reference counted typesHow do I create a global, mutable singleton?Share i32 mutably between threadsCompiler says that data cannot be shared between threads safely even though the data is wrapped within a MutexHow to respond with a different value depending on the state of the Rocket server?Is there a faster/shorter way to initialize variables in a Rust struct?How to parse multipart forms using abonander/multipart with Rocket?Can I render a Template in Rocket with my own serialized struct?Can't return String from Rocket routeHow do I respond from a Rocket handler with content type application/hal+json?Rocket not parsing RawStr in a URL to match routeI want to start Rocket in a module out of `main()` but failedRocket port override from environment variable not working in WindowsIs there a way to create a central routing file which contains only routes and the functions they are for in Rocket?Access a variable that is inside an if statement






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















I have a variable that gets initialized in main (line 9) and I want to access a reference to this variable inside of one of my route handlers.



#[get("/")]
fn index() -> String
return fetch_data::fetch(format!("posts"), &redis_conn).unwrap(); // How can I get redis_conn?


fn main()
let redis_conn = fetch_data::get_redis_connection(); // initialized here

rocket::ignite().mount("/", routes![index]).launch();



In other languages, this problem would be solvable by using global variables.










share|improve this question
































    0















    I have a variable that gets initialized in main (line 9) and I want to access a reference to this variable inside of one of my route handlers.



    #[get("/")]
    fn index() -> String
    return fetch_data::fetch(format!("posts"), &redis_conn).unwrap(); // How can I get redis_conn?


    fn main()
    let redis_conn = fetch_data::get_redis_connection(); // initialized here

    rocket::ignite().mount("/", routes![index]).launch();



    In other languages, this problem would be solvable by using global variables.










    share|improve this question




























      0












      0








      0








      I have a variable that gets initialized in main (line 9) and I want to access a reference to this variable inside of one of my route handlers.



      #[get("/")]
      fn index() -> String
      return fetch_data::fetch(format!("posts"), &redis_conn).unwrap(); // How can I get redis_conn?


      fn main()
      let redis_conn = fetch_data::get_redis_connection(); // initialized here

      rocket::ignite().mount("/", routes![index]).launch();



      In other languages, this problem would be solvable by using global variables.










      share|improve this question
















      I have a variable that gets initialized in main (line 9) and I want to access a reference to this variable inside of one of my route handlers.



      #[get("/")]
      fn index() -> String
      return fetch_data::fetch(format!("posts"), &redis_conn).unwrap(); // How can I get redis_conn?


      fn main()
      let redis_conn = fetch_data::get_redis_connection(); // initialized here

      rocket::ignite().mount("/", routes![index]).launch();



      In other languages, this problem would be solvable by using global variables.







      rust rust-rocket






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 27 at 19:09









      Shepmaster

      177k22 gold badges392 silver badges555 bronze badges




      177k22 gold badges392 silver badges555 bronze badges










      asked Mar 27 at 18:27









      MaxMax

      11212 bronze badges




      11212 bronze badges

























          1 Answer
          1






          active

          oldest

          votes


















          1















          Please read the Rocket documentation, specifically the section on state.



          Use State and Rocket::manage to have shared state:



          #![feature(proc_macro_hygiene, decl_macro)]

          #[macro_use]
          extern crate rocket; // 0.4.2

          use rocket::State;

          struct RedisThing(i32);

          #[get("/")]
          fn index(redis: State<RedisThing>) -> String
          redis.0.to_string()


          fn main()
          let redis = RedisThing(42);

          rocket::ignite()
          .manage(redis)
          .mount("/", routes![index])
          .launch();



          If you want to mutate the value inside the State, you will need to wrap it in a Mutex or other type of thread-safe interior mutability.



          See also:



          • Compiler says that data cannot be shared between threads safely even though the data is wrapped within a Mutex

          • Need holistic explanation about Rust's cell and reference counted types

          • Share i32 mutably between threads


          this problem would be solvable by using global variables.




          See also:



          • How do I create a global, mutable singleton?





          share|improve this answer


























            Your Answer






            StackExchange.ifUsing("editor", function ()
            StackExchange.using("externalEditor", function ()
            StackExchange.using("snippets", function ()
            StackExchange.snippets.init();
            );
            );
            , "code-snippets");

            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "1"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader:
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            ,
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );













            draft saved

            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55384204%2fhow-can-i-pass-a-variable-initialized-in-main-to-a-rocket-route-handler%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            1















            Please read the Rocket documentation, specifically the section on state.



            Use State and Rocket::manage to have shared state:



            #![feature(proc_macro_hygiene, decl_macro)]

            #[macro_use]
            extern crate rocket; // 0.4.2

            use rocket::State;

            struct RedisThing(i32);

            #[get("/")]
            fn index(redis: State<RedisThing>) -> String
            redis.0.to_string()


            fn main()
            let redis = RedisThing(42);

            rocket::ignite()
            .manage(redis)
            .mount("/", routes![index])
            .launch();



            If you want to mutate the value inside the State, you will need to wrap it in a Mutex or other type of thread-safe interior mutability.



            See also:



            • Compiler says that data cannot be shared between threads safely even though the data is wrapped within a Mutex

            • Need holistic explanation about Rust's cell and reference counted types

            • Share i32 mutably between threads


            this problem would be solvable by using global variables.




            See also:



            • How do I create a global, mutable singleton?





            share|improve this answer































              1















              Please read the Rocket documentation, specifically the section on state.



              Use State and Rocket::manage to have shared state:



              #![feature(proc_macro_hygiene, decl_macro)]

              #[macro_use]
              extern crate rocket; // 0.4.2

              use rocket::State;

              struct RedisThing(i32);

              #[get("/")]
              fn index(redis: State<RedisThing>) -> String
              redis.0.to_string()


              fn main()
              let redis = RedisThing(42);

              rocket::ignite()
              .manage(redis)
              .mount("/", routes![index])
              .launch();



              If you want to mutate the value inside the State, you will need to wrap it in a Mutex or other type of thread-safe interior mutability.



              See also:



              • Compiler says that data cannot be shared between threads safely even though the data is wrapped within a Mutex

              • Need holistic explanation about Rust's cell and reference counted types

              • Share i32 mutably between threads


              this problem would be solvable by using global variables.




              See also:



              • How do I create a global, mutable singleton?





              share|improve this answer





























                1














                1










                1









                Please read the Rocket documentation, specifically the section on state.



                Use State and Rocket::manage to have shared state:



                #![feature(proc_macro_hygiene, decl_macro)]

                #[macro_use]
                extern crate rocket; // 0.4.2

                use rocket::State;

                struct RedisThing(i32);

                #[get("/")]
                fn index(redis: State<RedisThing>) -> String
                redis.0.to_string()


                fn main()
                let redis = RedisThing(42);

                rocket::ignite()
                .manage(redis)
                .mount("/", routes![index])
                .launch();



                If you want to mutate the value inside the State, you will need to wrap it in a Mutex or other type of thread-safe interior mutability.



                See also:



                • Compiler says that data cannot be shared between threads safely even though the data is wrapped within a Mutex

                • Need holistic explanation about Rust's cell and reference counted types

                • Share i32 mutably between threads


                this problem would be solvable by using global variables.




                See also:



                • How do I create a global, mutable singleton?





                share|improve this answer















                Please read the Rocket documentation, specifically the section on state.



                Use State and Rocket::manage to have shared state:



                #![feature(proc_macro_hygiene, decl_macro)]

                #[macro_use]
                extern crate rocket; // 0.4.2

                use rocket::State;

                struct RedisThing(i32);

                #[get("/")]
                fn index(redis: State<RedisThing>) -> String
                redis.0.to_string()


                fn main()
                let redis = RedisThing(42);

                rocket::ignite()
                .manage(redis)
                .mount("/", routes![index])
                .launch();



                If you want to mutate the value inside the State, you will need to wrap it in a Mutex or other type of thread-safe interior mutability.



                See also:



                • Compiler says that data cannot be shared between threads safely even though the data is wrapped within a Mutex

                • Need holistic explanation about Rust's cell and reference counted types

                • Share i32 mutably between threads


                this problem would be solvable by using global variables.




                See also:



                • How do I create a global, mutable singleton?






                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Aug 21 at 17:22

























                answered Mar 27 at 18:52









                ShepmasterShepmaster

                177k22 gold badges392 silver badges555 bronze badges




                177k22 gold badges392 silver badges555 bronze badges





















                    Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.







                    Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.



















                    draft saved

                    draft discarded
















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid


                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.

                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55384204%2fhow-can-i-pass-a-variable-initialized-in-main-to-a-rocket-route-handler%23new-answer', 'question_page');

                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                    Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

                    Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript