A thermostat keeps a target temperature, and the target must always stay between 10 and 30 degrees. If any code could change the target directly, nothing would stop it from setting 95. So the target is a private field: only the thermostat's own methods change it, and every one of them keeps it between 10 and 30.
As in the Access Modifiers lesson, a Rust struct field is private by default: without pub, code in other modules can't read or change it. Write:
- The
Thermostatstruct, with one private field,target(ani32). Thermostat::new(): returns a thermostat whose target is 20.set_target(t)sets the target tot. A value below 10 sets it to 10, and a value above 30 sets it to 30.warmer()raises the target by 1 andcooler()lowers it by 1, but neither ever takes it outside 10 to 30: at 30,warmer()leaves it at 30, and at 10,cooler()leaves it at 10.get_target()returns the target. It is the only way for other code to read it.
The methods that change the target take &mut self; get_target only reads, so it takes &self. The starter code already has these headers.
The input is a list of operations, applied in order to one new thermostat made by Thermostat::new(). The output lists what the get_target calls return, in order.
Example 1:
Input:
get_target()
warmer()
warmer()
get_target()
cooler()
get_target()
Output: 20 22 21
Explanation: A new thermostat starts at 20. Two warmer() calls take it to 22, and cooler() brings it back to 21.
Example 2:
Input:
set_target(35)
get_target()
warmer()
get_target()
cooler()
get_target()
Output: 30 30 29
Explanation: 35 is above 30, so the target becomes 30. warmer() can't go past 30, so the target stays 30.
cooler() lowers it to 29.
Example 3:
Input:
set_target(4)
get_target()
cooler()
get_target()
set_target(10)
warmer()
get_target()
Output: 10 10 11
Explanation: 4 is below 10, so the target becomes 10, and cooler() can't go below 10. set_target(10) keeps 10,
since 10 itself is allowed, and warmer() raises it to 11.
Constraints:
-1000 <= t <= 1000- A test case has from 1 to 1000 operations, and at least one of them is
get_target.
Free plan: 30 tutor messages. PRO is unlimited.
