### Start the Quiz Server Source: https://context7.com/dtolnay/rust-quiz/llms.txt Execute the development server to compile questions and serve the application locally. ```bash # Compile questions and serve the quiz at http://localhost:8000/rust-quiz/ cargo run -- serve ``` -------------------------------- ### Examples of Rust Statements Source: https://github.com/dtolnay/rust-quiz/blob/master/questions/001-macro-count-statements.md Demonstrates various constructs that qualify as statements within a function body. ```rust // Items are statements. struct S { x: u64 } // Let-bindings are statements. let mut s = S { x: 1 } // Expressions are statements. s.x + 1 ``` -------------------------------- ### Rust Ownership and Drop Example Source: https://github.com/dtolnay/rust-quiz/blob/master/questions/025-unit-infallible-match.md Illustrates how values are dropped when they no longer have an owner. Pay attention to when `S` is dropped and why. ```rust struct S; impl Drop for S { fn drop(&mut self) { println!("Dropping S"); } } fn f() -> S { S } fn main() { let S = f(); let _ = f(); } ``` -------------------------------- ### Macro Invocation with Statements Source: https://github.com/dtolnay/rust-quiz/blob/master/questions/001-macro-count-statements.md Shows an example of passing multiple statements into a macro that uses << as a separator. ```rust m! { struct S { x: u64 } let mut s = S { x: 1 } s.x + 1 } ``` -------------------------------- ### Start Local HTTP Server with Hyper Source: https://context7.com/dtolnay/rust-quiz/llms.txt Initializes a local HTTP server on port 8000 using Hyper and Tokio. It listens for incoming TCP connections and spawns a new task for each connection to handle HTTP requests. ```rust use hyper::server::conn::http1; use hyper::service::Service; use tokio::net::TcpListener; const PORT: u16 = 8000; pub async fn main() -> Result<(), Error> { let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), PORT); let listener = TcpListener::bind(addr).await?; eprintln!("Quiz server running on http://localhost:{}/ ...", PORT); loop { let (tcp_stream, _) = listener.accept().await?; let io = TokioIo::new(tcp_stream); tokio::task::spawn(async move { let _ = http1::Builder::new() .serve_connection(io, MainService::new()) .await; }); } } // Service redirects "/" to "/rust-quiz/" and serves static files impl Service> for MainService { fn call(&self, req: Request) -> Self::Future { if req.uri().path() == "/" { MainFuture::Root // Redirect to /rust-quiz/ } else { MainFuture::Static(Box::pin(self.staticfile.clone().serve(req))) } } } ``` -------------------------------- ### Define Rust macro_rules! with tokenization examples Source: https://github.com/dtolnay/rust-quiz/blob/master/questions/008-tokenize-punctuation.md This macro demonstrates how macro_rules! tokenizes input patterns. Note that the first and third rules are identical due to tokenization, making the third rule unreachable. ```rust macro_rules! m { (== >) => { print!("1"); }; (= = >) => { print!("2"); }; (== >) => { print!("3"); }; (= =>) => { print!("4"); }; } ``` -------------------------------- ### Never Type Usage Example Source: https://github.com/dtolnay/rust-quiz/blob/master/questions/021-closure-or-logical-or.md Demonstrates the use of the never type (!) in a function returning a boolean. ```rust fn f() -> bool { unimplemented!() } ``` -------------------------------- ### C++ Inheritance and Method Dispatch Example Source: https://github.com/dtolnay/rust-quiz/blob/master/questions/027-subtrait-dispatch.md Demonstrates C++'s virtual method dispatch with inheritance, where derived class methods override base class methods, leading to different output compared to Rust's trait system. ```cpp #include struct Base { virtual void method() const { std::cout << "1"; } }; struct Derived: Base { void method() const { std::cout << "2"; } }; void dynamic_dispatch(const Base &x) { x.method(); } template void static_dispatch(const T x) { x.method(); } int main() { dynamic_dispatch(Derived{}); static_dispatch(Derived{}); } ``` -------------------------------- ### Rust Ownership and Move Example Source: https://github.com/dtolnay/rust-quiz/blob/master/questions/019-dropped-by-underscore.md This snippet demonstrates a core concept in Rust: whether a variable is moved or not when used in an expression without explicit binding. The output depends on this behavior. ```rust let _ = s; ``` -------------------------------- ### Rust Macro Opaque Specifier Example Source: https://github.com/dtolnay/rust-quiz/blob/master/questions/009-opaque-metavariable.md Demonstrates how $:lifetime specifiers do not become opaque, allowing inspection by subsequent macro rules. ```rust macro_rules! m { ('a) => {}; } macro_rules! l { ($l:lifetime) => { // $l is not opaque. m!($l); } } l!('a); ``` -------------------------------- ### Rust Closure Capture by Value Example Source: https://github.com/dtolnay/rust-quiz/blob/master/questions/036-fnmut-copy.md Illustrates a struct representing a closure capturing an i32 by value. This struct implements Copy and Clone, allowing multiple independent instances. ```rust #[derive(Copy, Clone)] pub struct UnnameableClosure { i: i32, } impl UnnameableClosure { pub fn unnameable_call_operator(&mut self) { self.i += 1; print!("{}", self.i); } } let mut i = 0i32; g(UnnameableClosure { i }); ``` -------------------------------- ### Statement Semicolon Requirements Source: https://github.com/dtolnay/rust-quiz/blob/master/questions/001-macro-count-statements.md Examples illustrating which expressions require a trailing semicolon to be valid statements. ```rust // No trailing semicolon required. for t in vec { /* ... */ } // Trailing semicolon required. self.skip_whitespace()?; ``` -------------------------------- ### Rust Closure Capture by Mutable Reference Example Source: https://github.com/dtolnay/rust-quiz/blob/master/questions/036-fnmut-copy.md Shows a struct representing a closure capturing a mutable reference to an i32. This prevents Copy and Clone due to aliasing mutable references. ```rust pub struct UnnameableClosure<'a> { i: &'a mut i32, } ``` -------------------------------- ### Rust Trait Implementation for Trait Object Source: https://github.com/dtolnay/rust-quiz/blob/master/questions/027-subtrait-dispatch.md This is an example of how Rust might internally implement a trait for a trait object. It shows the concept of forwarding calls to the underlying type's implementation. ```rust impl Base for (dyn Base) { fn method(&self) { /* Some automatically generated implementation detail that ends up calling the right type's impl of the trait method Base::method. */ } } ``` -------------------------------- ### Rust Closure Parsing Example Source: https://github.com/dtolnay/rust-quiz/blob/master/questions/002-bitand-or-reference.md This closure is parsed differently due to an empty block statement followed by a reference. It results in a different type compared to closures that use user-defined operators. ```rust let i = || { {} &S(4) }; ``` -------------------------------- ### Break expression parsing behavior Source: https://github.com/dtolnay/rust-quiz/blob/master/questions/020-break-return-in-condition.md Demonstrates how the break keyword in an if-statement condition does not eagerly parse a value starting with a curly brace, unlike the return keyword. ```rust loop { if break { print!("2") } {} } ``` -------------------------------- ### Serve Rust Quiz Locally Source: https://github.com/dtolnay/rust-quiz/blob/master/README.md Run this command to package all questions into a JavaScript file and serve the website locally over HTTP. ```bash cargo run -- serve ``` -------------------------------- ### Create New Question Files Source: https://context7.com/dtolnay/rust-quiz/llms.txt Commands to initialize the required files for a new quiz question in the questions directory. ```bash # Create question files with number 000 (will be assigned on merge) touch questions/000-my-question-name.rs touch questions/000-my-question-name.md ``` -------------------------------- ### Initialize Frontend Quiz Logic Source: https://context7.com/dtolnay/rust-quiz/llms.txt Sets up event listeners for quiz interactions and initializes the quiz state. This function should be called when the page loads. ```javascript // Initialize quiz and load random question function init() { form.addEventListener("submit", checkAnswer); buttonNext.onclick = nextQuestion; buttonHint.onclick = doHint; buttonSkip.onclick = nextQuestion; buttonReveal.onclick = doReveal; total.innerHTML = countQuestions(); loadState(); updateProgress(); initQuestion(); activateQuestion(); } ``` -------------------------------- ### Demonstrating Clone for References Source: https://github.com/dtolnay/rust-quiz/blob/master/questions/030-clone-pointers.md Illustrates how cloning a reference (&T) results in a new reference pointing to the same data, not a deep copy of the data itself. This behavior is crucial when dealing with types that do not implement Clone. ```rust fn p(_: X) { println!("{}", std::mem::size_of::()); } struct A; fn main() { let a = A; let a_ref = &a; p(a_ref); p(a_ref.clone()); let b = (); let b_ref = &b; p(b_ref); p(b_ref.clone()); } ``` -------------------------------- ### Byte-string slicing and indexing Source: https://github.com/dtolnay/rust-quiz/blob/master/questions/004-dotdot-in-tuple.md Demonstrates slicing a byte-string literal with RangeFull and accessing an element by index. ```rust b"066"[..][1] ``` -------------------------------- ### Rest pattern usage Source: https://github.com/dtolnay/rust-quiz/blob/master/questions/004-dotdot-in-tuple.md Demonstrates the use of .. as a rest pattern to match multiple elements in a tuple. ```rust (.., x, y) ``` -------------------------------- ### Shadowing and Assignment Expression Equivalent Source: https://github.com/dtolnay/rust-quiz/blob/master/questions/006-value-of-assignment.md Demonstrates the equivalent logic of the quiz code after accounting for variable shadowing and assignment expression evaluation. ```rust let a; let b = a = true; print!("{}", mem::size_of_val(&b)); ``` ```rust let a = true; let b = (); print!("{}", mem::size_of_val(&b)); ``` -------------------------------- ### Define Question Code Source: https://context7.com/dtolnay/rust-quiz/llms.txt Template for the Rust source file of a new question. ```rust // questions/000-my-question-name.rs fn main() { // Your tricky Rust code here // Aim for <25 lines, <40 columns print!("{}", some_surprising_result()); } ``` -------------------------------- ### Configure Google Analytics tracking Source: https://github.com/dtolnay/rust-quiz/blob/master/docs/13/index.html Initializes the Google Analytics data layer and configures tracking parameters for the site. ```javascript window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'G-RQ70RHVVSD', {anonymize_ip: true, cookie_domain: 'dtolnay.github.io', cookie_flags: 'samesite=strict;secure'}); ``` -------------------------------- ### Define a Quiz Question Source: https://context7.com/dtolnay/rust-quiz/llms.txt The Rust source file containing the code to be evaluated by the user. ```rust // questions/001-macro-count-statements.rs macro_rules! m { ($($s:stmt)*) => { $( { stringify!($s); 1 } )<<* }; } fn main() { print!( "{}{}{}", m! { return || true }, m! { (return) || true }, m! { {return} || true }, ); } ``` -------------------------------- ### Const substitution behavior Source: https://github.com/dtolnay/rust-quiz/blob/master/questions/003-mutate-const.md Demonstrates how const items are substituted in expression positions, effectively creating new instances. ```rust struct S { x: i32, } fn main() { let v = &mut S { x: 2 }; v.x += 1; S { x: 2 }.x += 1; print!("{}{}", v.x, S { x: 2 }.x); } ``` ```rust let mut _tmp0 = S { x: 2 }; let v = &mut _tmp0; ``` -------------------------------- ### Equivalent program for double negation Source: https://github.com/dtolnay/rust-quiz/blob/master/questions/016-prefix-decrement.md Demonstrates how the compiler interprets the double negation expression in the context of the quiz. ```rust fn main() { let mut x = 4; 4; print!("{}{}", 4, 4); } ``` -------------------------------- ### RangeFull expression usage Source: https://github.com/dtolnay/rust-quiz/blob/master/questions/004-dotdot-in-tuple.md Demonstrates the use of .. as a RangeFull type within a tuple expression. ```rust (0, 1, ..) ``` -------------------------------- ### Process Questions with Rayon Source: https://context7.com/dtolnay/rust-quiz/llms.txt The render module logic for parallel processing of question files and generation of the JavaScript data file. ```rust use rayon::ThreadPoolBuilder; use std::collections::BTreeMap; use parking_lot::Mutex; // Main render function that processes all questions pub fn main() -> Result<(), Error> { let mut question_files = Vec::new(); for entry in fs::read_dir("questions")? { let path = entry?.path(); if path.to_string_lossy().ends_with(".rs") { question_files.push(path); } } question_files.sort(); let cpus = num_cpus::get(); let pool = ThreadPoolBuilder::new() .num_threads(cpus) .build() .map_err(Error::Rayon)?; let questions = Mutex::new(BTreeMap::new()); pool.scope(|scope| { for _ in 0..cpus { scope.spawn(|_| worker(&oqueue, &question_files, &questions)); } }); // Write compiled questions to JavaScript file let json_object = serde_json::to_string_pretty(&questions.into_inner())?; let javascript = format!("var questions = {};\n", json_object); fs::write("docs/questions.js", javascript)?; Ok(()) } ``` -------------------------------- ### Demonstrate Operator Precedence with Negative Literals Source: https://github.com/dtolnay/rust-quiz/blob/master/questions/022-macro-tokenize-number.md Shows how the expression -3i32.pow(4) is parsed as -(3i32.pow(4)) due to operator precedence rules. ```rust fn main() { let n = -3i32.pow(4); println!("{}", n); } ``` -------------------------------- ### Load Quiz State from Local Storage Source: https://context7.com/dtolnay/rust-quiz/llms.txt Retrieves the user's quiz progress (answered questions) from localStorage. If no data is found, it initializes the state as an empty object. ```javascript // Load answered questions from localStorage function loadState() { if (storageAvailable()) { var json = window.localStorage.getItem("rust-quiz-answered"); state = json ? JSON.parse(json) : {}; } } ``` -------------------------------- ### Define Question Metadata Source: https://context7.com/dtolnay/rust-quiz/llms.txt Template for the markdown file containing the answer, difficulty, hint, and explanation. ```markdown Answer: 42 Difficulty: 2 # Hint One brief sentence about what to consider. # Explanation Detailed explanation of the surprising behavior, with links to relevant Rust documentation. ``` -------------------------------- ### Demonstrate Parse Error with Partial Parenthesizing Source: https://github.com/dtolnay/rust-quiz/blob/master/questions/033-range-full-method.md Shows the compiler error encountered when attempting to partially parenthesize a closure and range method call. ```text error: expected one of `)` or `,`, found `.` --> src/main.rs:22:13 | 22 | (|| (.. .method()))(); | -^ expected one of `)` or `,` | | | help: missing `,` ``` -------------------------------- ### Activate Question Logic Source: https://context7.com/dtolnay/rust-quiz/llms.txt JavaScript function to toggle between the quiz form and the tombstone warning. ```javascript function activateQuestion() { if (questions[q].answer) { show(form); hide(tombstone); } else { hide(form); show(tombstone); // "This question is no longer part of the Rust Quiz" } } ``` -------------------------------- ### Variable and Constant Declaration in Rust Source: https://github.com/dtolnay/rust-quiz/blob/master/questions/024-local-and-const-hygiene.md Demonstrates the declaration of a local variable 'x' and a constant 'K' within the main function scope. Note that 'x' is highlighted to indicate its status as a local variable. ```rust let x: u8 = 1; const K: u8 = 2; ``` -------------------------------- ### Demonstrate early bound type parameter inference error Source: https://github.com/dtolnay/rust-quiz/blob/master/questions/011-function-pointer-comparison.md Type parameters are early bound, requiring them to be resolved during monomorphization. ```rust fn m() {} fn main() { let m1 = m::; // ok let m2 = m; // error: cannot infer type for `T` } ``` -------------------------------- ### Clone with Rc Source: https://github.com/dtolnay/rust-quiz/blob/master/questions/030-clone-pointers.md Demonstrates cloning an Rc (Reference Counted pointer). It highlights that cloning an Rc increments the reference count rather than cloning the underlying data. The idiomatic way to clone an Rc is `Rc::clone(&c)`. ```rust use std::rc::Rc; fn p(_: X) { println!("{}", std::mem::size_of::()); } fn main() { let c = Rc::new(()); // Rc<()> p(c.clone()); // Clones the Rc, increments ref count p(Rc::clone(&c)); // Idiomatic way to clone Rc } ``` -------------------------------- ### Demonstrate Macro Hygiene and Scope in Rust Source: https://github.com/dtolnay/rust-quiz/blob/master/questions/035-decl-macro-hygiene.md This code snippet illustrates how Rust's macro hygiene prevents unintended variable shadowing by ensuring that macro-introduced bindings do not interfere with existing variables at the call site. The output demonstrates the actual behavior concerning scope and variable dropping. ```rust fn main() { let a = X(1); let a = X(2); print!("{}", a.0); } ``` -------------------------------- ### Question Data Structure Source: https://context7.com/dtolnay/rust-quiz/llms.txt The serialized JSON structure used by the frontend to display questions. ```javascript // docs/questions.js - generated file var questions = { "1": { "code": "macro_rules! m { ... }", "difficulty": 3, "answer": "112", "hint": "

The expression evaluates to...

", "explanation": "

This question revolves around...

" }, "2": { // Next question... } }; ``` -------------------------------- ### Mutex Guard Lifetime Management Source: https://github.com/dtolnay/rust-quiz/blob/master/questions/028-underscore-prefix.md Demonstrates the correct usage of a mutex guard to ensure the lock is held for the duration of the critical section. ```rust use std::sync::Mutex; static MUTEX: Mutex<()> = Mutex::new(()); /// MUTEX must be held when accessing this value. static mut VALUE: usize = 0; fn main() { let _guard = MUTEX.lock().unwrap(); unsafe { VALUE += 1; } } ``` -------------------------------- ### Expanded String Literals Source: https://github.com/dtolnay/rust-quiz/blob/master/questions/001-macro-count-statements.md The result of the stringify! macro expansion within the expression. ```rust { "struct S { x: u64 }"; 1 } << { "let mut s = S { x: 1 }"; 1 } << { "s.x + 1"; 1 } ``` -------------------------------- ### Verify Rust Answer Compilation Source: https://context7.com/dtolnay/rust-quiz/llms.txt Compiles and runs Rust code to verify answers, handling compilation errors and expected output. Ensure the Rust compiler is available in the system's PATH. ```rust fn check_answer(rs_path: &Path, expected: &str, warnings: &[String]) -> Result<(), Error> { let out_dir = env::temp_dir().join("rust-quiz"); // Compile with warnings denied (except explicitly allowed) let mut cmd = Command::new("rustc"); cmd.arg(rs_path) .arg("--edition=2021") .arg("--out-dir") .arg(&out_dir) .arg("--deny=warnings"); for warning in warnings { cmd.arg("--allow").arg(warning); } let status = cmd.status().map_err(Error::Rustc)?; match (expected, status.success()) { ("undefined", true) => Ok(()), // UB programs should compile ("error", false) => Ok(()), // Error programs should not compile (output, true) => run(&out_dir, rs_path, output), // Check actual output _ => Err(Error::ShouldCompile), } } fn run(out_dir: &Path, rs_path: &Path, expected: &str) -> Result<(), Error> { let stem = rs_path.file_stem().unwrap(); let exe = out_dir.join(stem).with_extension(EXE_EXTENSION); let output = Command::new(exe).output().map_err(Error::Execute)?; let output = String::from_utf8(output.stdout)?; if output == expected { Ok(()) } else { Err(Error::WrongOutput { expected: expected.to_owned(), output }) } } ``` -------------------------------- ### Define Question Metadata Source: https://context7.com/dtolnay/rust-quiz/llms.txt The Markdown file format required for each quiz question. ```markdown Answer: 112 Difficulty: 2 # Hint Brief hint text (maximum 3 lines, 2 sentences ideal). # Explanation Detailed explanation of why the program behaves as it does. Include code examples and links to documentation. ``` ```text Answer: # "undefined", "error", or a numeric output Difficulty: <1|2|3> # 1=easy, 2=medium, 3=hard Warnings: # comma-separated list of allowed warnings # Hint # Explanation ``` -------------------------------- ### Rust Function Type Coercion to Function Pointer Source: https://github.com/dtolnay/rust-quiz/blob/master/questions/034-fn-pointer-vs-fn-type.md Demonstrates how a Rust function type can be coerced into a function pointer. This coercion results in a pointer-sized type at runtime, unlike the zero-sized function type itself. ```rust fn main() { let mut x: u8 = 5; let a = |mut x: u8| x; let b = a::; let c = b as fn(u8) -> u8; d(c); d(b) } fn d(_: fn(T)) {} ``` -------------------------------- ### Demonstrate late bound lifetime parameter behavior Source: https://github.com/dtolnay/rust-quiz/blob/master/questions/011-function-pointer-comparison.md Lifetime parameters on functions are late bound by default, allowing them to be determined at the call site. ```rust fn m<'a>(_: &'a ()) {} fn main() { let m1 = m; // ok even though 'a isn't provided } ``` -------------------------------- ### Block Expression Parsing Source: https://github.com/dtolnay/rust-quiz/blob/master/questions/001-macro-count-statements.md Demonstrates how block expressions terminate an expression, preventing the parser from consuming subsequent operators. ```rust fn f() -> &'static &'static bool { // Block expression. { println!("What a silly function."); } // Reference to reference to true. &&true } ``` -------------------------------- ### Rust Expression Evaluation without Increment/Decrement Source: https://github.com/dtolnay/rust-quiz/blob/master/questions/017-unary-decrement.md Demonstrates how Rust evaluates expressions without direct increment/decrement operators, using negation to achieve similar results. This is relevant when dealing with arithmetic operations that might otherwise use `++` or `--` in other languages. ```rust let a = 5; let b = 3; let result = a - (-(-(-(-b)))); // Equivalent to a - b in this context println!("{}", result); // Output: 2 ``` -------------------------------- ### Define Answer Types Source: https://context7.com/dtolnay/rust-quiz/llms.txt Supported answer formats for quiz questions. ```javascript // Undefined behavior - program compiles but has UB { answer: "undefined" } // Compilation error - program does not compile { answer: "error" } // Deterministic output - program prints this exact string { answer: "112" } ``` -------------------------------- ### Retire a Question Source: https://context7.com/dtolnay/rust-quiz/llms.txt Set the markdown content of a question to 'tombstone' to disable it. ```markdown tombstone ``` -------------------------------- ### Nested Scope with Shadowing in Rust Source: https://github.com/dtolnay/rust-quiz/blob/master/questions/024-local-and-const-hygiene.md Illustrates a nested scope where a new local variable 'x' shadows the outer 'x', and a new constant 'K' shadows the outer 'K'. The macro 'm!' is called within this scope. ```rust { let x: u8 = 3; const K: u8 = 4; m!(); } ``` -------------------------------- ### Reset Quiz Progress Source: https://context7.com/dtolnay/rust-quiz/llms.txt Clears all user progress data from the application state and localStorage, resetting the quiz to its initial state. ```javascript // Reset all progress function reset() { state = {}; window.localStorage.clear(); answered.innerHTML = 0; } ``` -------------------------------- ### Macro Expansion Result Source: https://github.com/dtolnay/rust-quiz/blob/master/questions/001-macro-count-statements.md The expanded form of the macro invocation using the << separator. ```rust { stringify!(struct S { x: u64 }); 1 } << { stringify!(let mut s = S { x: 1 }); 1 } << { stringify!(s.x + 1); 1 } ``` -------------------------------- ### Rust Macro Definition with Variable and Constant Usage Source: https://github.com/dtolnay/rust-quiz/blob/master/questions/024-local-and-const-hygiene.md Defines a macro 'm!' that prints two values. The usage of 'x' within the macro refers to the lexically scoped local variable, while 'K' refers to a constant that is not subject to the same hygiene rules. ```rust macro_rules! m { () => { print!("{}{}", x, K); }; } ``` -------------------------------- ### Parse Block Followed by Binary Operator in Rust Source: https://github.com/dtolnay/rust-quiz/blob/master/questions/001-macro-count-statements.md Use parentheses to wrap a block when it's followed by a binary operator to ensure correct parsing. This prevents the parser from terminating the expression at the closing curly brace. ```rust fn f() -> bool { ({ true } && true) } ``` -------------------------------- ### Demonstrate invalid lifetime bounds in HRTB Source: https://github.com/dtolnay/rust-quiz/blob/master/questions/011-function-pointer-comparison.md Late bound lifetimes cannot have explicit bounds in the 'for' syntax. ```rust error: lifetime bounds cannot be used in this context --> src/main.rs:5:20 | 5 | let _: for<'b: 'a> fn(&'b ()); | ^^ ``` -------------------------------- ### Record Correct Answer and Save State Source: https://context7.com/dtolnay/rust-quiz/llms.txt Marks the current question as answered correctly, updates the quiz state, saves the state to localStorage, and refreshes the progress display. ```javascript // Save state when user answers correctly function recordCorrect() { loadState(); state[q] = true; saveState(); updateProgress(); } ``` -------------------------------- ### Select Random Unanswered Question Source: https://context7.com/dtolnay/rust-quiz/llms.txt Picks a random question to display. It prioritizes unanswered questions but will select from any available question if all have been answered. ```javascript // Pick random unanswered question, or any if all answered function pickRandomQuestion() { var candidates = []; var unanswered = []; for (var i in questions) { var number = parseInt(i, 10); if (!isNaN(number) && number !== q && questions[number].answer) { candidates.push(number); if (!state[number]) { unanswered.push(number); } } } candidates = unanswered.length > 0 ? unanswered : candidates; q = candidates[Math.floor(Math.random() * candidates.length)]; } ``` -------------------------------- ### Demonstrate invalid explicit lifetime specification Source: https://github.com/dtolnay/rust-quiz/blob/master/questions/011-function-pointer-comparison.md Attempting to specify late bound lifetime parameters explicitly results in a compilation error. ```rust // error: cannot specify lifetime arguments explicitly if late bound lifetime parameters are present let m2 = m::<'static>; ``` ```rust // error: cannot specify lifetime arguments explicitly if late bound lifetime parameters are present let m3 = m::<'_>; ``` -------------------------------- ### Rust Program Comment Source: https://github.com/dtolnay/rust-quiz/blob/master/docs/20/index.html This is a comment within a Rust program indicating that JavaScript is required for its execution, though the actual Rust code is not provided. ```rust // JavaScript is required (sorry) ``` -------------------------------- ### Attempting to call inherent method on dyn Trait Source: https://github.com/dtolnay/rust-quiz/blob/master/questions/010-shadowed-trait-object-method.md Demonstrates syntax attempts to invoke an inherent method on a trait object that is shadowed by a trait method. ```rust ::f(&true); ::f(&true as &dyn Trait); ``` -------------------------------- ### Reset quiz state Source: https://github.com/dtolnay/rust-quiz/blob/master/docs/1/index.html Resets the current quiz session state. ```javascript javascript:reset() ``` -------------------------------- ### Expressing function types with HRTB Source: https://github.com/dtolnay/rust-quiz/blob/master/questions/011-function-pointer-comparison.md The 'for' keyword is used to express higher-ranked trait bounds for late bound lifetimes. ```rust let m1: impl for<'r> Fn(&'r ()) = m; ``` -------------------------------- ### Define Error Types Source: https://context7.com/dtolnay/rust-quiz/llms.txt The Error enum defines all possible failure states for the quiz validation system. ```rust #[derive(Error, Debug)] pub enum Error { #[error("program compiled with warnings")] CompiledWithWarnings, #[error("wrong filename format")] FilenameFormat, #[error("{0} does not match the expected format")] MarkdownFormat(PathBuf), #[error("program failed to compile")] ShouldCompile, #[error("program should fail to compile")] ShouldNotCompile, #[error("wrong output! expected: {expected}, actual: {output}")] WrongOutput { expected: String, output: String }, } ``` -------------------------------- ### Invoking a function pointer field Source: https://github.com/dtolnay/rust-quiz/blob/master/questions/018-method-or-function-pointer.md Use parentheses around the field access to invoke a function pointer stored in a struct field when a method of the same name exists. ```rust fn main() { let print2 = || print!("2"); (S { f: print2 }.f)(); } ``` -------------------------------- ### Check User's Quiz Answer Source: https://context7.com/dtolnay/rust-quiz/llms.txt Validates the user's submitted answer against the correct answer for the current question. It handles different answer types: undefined, error, or specific output. ```javascript // Check user's answer against correct answer function checkAnswer(e) { e.preventDefault(); var correct; if (radioUndefined.checked) { correct = questions[q].answer === "undefined"; } else if (radioError.checked) { correct = questions[q].answer === "error"; } else if (radioOutput.checked) { correct = questions[q].answer === textOutput.value.trim(); } if (correct) { show(explanationCorrect); recordCorrect(); showExplanation(); } else { show(incorrect); } } ``` -------------------------------- ### Compiler error for ambiguous method call Source: https://github.com/dtolnay/rust-quiz/blob/master/questions/010-shadowed-trait-object-method.md The error message generated by the Rust compiler when multiple items named 'f' are in scope for a trait object. ```text error[E0034]: multiple applicable items in scope --> questions/010.rs:18:5 | 18 | ::f(&true); | ^^^^^^^^^^^^^^ multiple `f` found | note: candidate #1 is defined in an impl for the type `dyn Trait` --> questions/010.rs:6:5 | 6 | fn f(&self) { | ^^^^^^^^^^^ note: candidate #2 is defined in the trait `Trait` --> questions/010.rs:2:5 | 2 | fn f(&self); | ^^^^^^^^^^^^ = help: to disambiguate the method call, write `Trait::f(...)` instead ``` -------------------------------- ### Reset Quiz State Source: https://github.com/dtolnay/rust-quiz/blob/master/docs/12/index.html Resets the current quiz progress via a JavaScript function call. ```javascript reset() ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.