A ticket machine gives every new ticket the next number: the first ticket gets 1, the next one 2, and so on. The counter belongs to all the tickets together, not to any one of them. Rust structs have no static fields: as in the Static Members lesson, the shared counter is a module-level static mut variable, read and changed only inside unsafe blocks. A function in the impl block that has no self is called on the type itself, like Ticket::new: that is Rust's static method. Each ticket keeps its own number, copied from the counter when the ticket is created.
Write:
- The
Ticketstruct, with two fields:name(aString) andnumber(ani32). - The module-level counter
static mut COUNT: i32, starting at 0. Ticket::new(name): it adds 1 toCOUNTand returns a newTicketwith that name and the new value ofCOUNTas its number.Ticket::issued(): returns how many tickets were created since the counter was last reset.Ticket::reset_counter(): sets the counter back to 0, so the next ticket gets number 1 again.
For each test case, the test code calls Ticket::reset_counter(), then creates one ticket per name with Ticket::new, in order. Once all the tickets of the case exist, it prints each ticket as its name, a space, # and its number, one ticket per line, and then the value of Ticket::issued() on a line of its own.
Example 1:
Input:
Ticket::new("Ann")
Ticket::new("Bob")
Ticket::new("Cy")
Output:
Ann #1
Bob #2
Cy #3
3
Explanation: reset_counter() set the counter to 0. Each new ticket adds 1 to it and keeps the new value,
so the tickets get 1, 2 and 3, and issued() returns 3.
Example 2:
Input:
Ticket::new("Mia")
Ticket::new("Mia")
Output:
Mia #1
Mia #2
2
Explanation: The number comes from the shared counter, not from the name, so the two tickets for Mia
get different numbers. The numbers start at 1 again because reset_counter() ran before this case.
Example 3:
Input:
(no tickets)
Output:
0
Explanation: reset_counter() set the counter to 0 and no ticket was created, so issued() returns 0.
Constraints:
- A test case creates from 0 to 1000 tickets.
- A name is one word of 1 to 20 English letters. Two tickets can have the same name.
- The tickets are printed only after all of them were created, so every ticket must store its own number: reading
COUNTwhen printing would give every ticket the last number.
Free plan: 30 tutor messages. PRO is unlimited.
