Решение на упр.02 задача 1 от Константин Георгиев
Към профила на Константин Георгиев
Резултати
- 4 точки от тестове
- 0 бонус точки
- 4 точки общо
- 0 успешни тест(а)
- 0 неуспешни тест(а)
Код
// SensorData does not implement Copy, so assigning it moves ownership.
#[derive(Debug)]
struct SensorData {
temperature: f64,
radiation_level: u32,
}
#[derive(Debug)]
struct Probe {
name: String,
battery_percentage: u8,
last_reading: SensorData,
status: String,
}
fn create_sensor_data(temperature: f64, radiation_level: u32) -> SensorData {
SensorData {
temperature,
radiation_level,
}
}
fn create_probe(name: &str, battery_percentage: u8, sensor_data: SensorData) -> Probe {
let battery = if battery_percentage > 100 {
100
} else {
battery_percentage
};
Probe {
name: name.to_string(),
battery_percentage: battery,
last_reading: sensor_data,
status: String::from("Standby"),
}
}
fn diagnostic_check(probe: &Probe) {
if probe.battery_percentage < 20 {
println!("Warning: Low battery ({}%) on probe '{}'.",
probe.battery_percentage, probe.name)
} else {
println!("{:?}", probe);
}
}
fn recharge_probe(probe: &mut Probe, amount: u8) {
let diff = 100 - probe.battery_percentage;
if amount > diff {
probe.battery_percentage = 100;
} else {
probe.battery_percentage += amount;
}
}
fn update_status(probe: &mut Probe, new_status: &str) {
probe.status = new_status.to_string();
}
// The function takes ownership of sensor. It is dropped when the function returns.
fn analyze_critical_sensor(sensor: SensorData) {
const MAX_RADIATION: u32 = 100;
const MIN_TEMPERATURE: f64 = -150.0;
const MAX_TEMPERATURE: f64 = 150.0;
let radiation_alarm = sensor.radiation_level > MAX_RADIATION;
let temperature_alarm = sensor.temperature < MIN_TEMPERATURE ||
sensor.temperature > MAX_TEMPERATURE;
if radiation_alarm || temperature_alarm {
if radiation_alarm {
println!("Warning: Critical radiation level ({})",
sensor.radiation_level);
}
if temperature_alarm {
println!("Warning: Extreme temperature ({})",
sensor.temperature);
}
} else {
println!("Everything is OK!");
}
}
fn main() {
let sensor_data_1 = create_sensor_data(-49.15, 12);
let mut probe1 = create_probe("Voyager-X", 15, sensor_data_1);
diagnostic_check(&probe1);
recharge_probe(&mut probe1, 70);
update_status(&mut probe1, "Exploring");
diagnostic_check(&probe1);
// last_reading is moved out of probe1 into reading.
// name, status and battery_percentage are still accessible,
// but probe1 as a whole can no longer be borrowed or moved.
let reading = probe1.last_reading;
analyze_critical_sensor(reading);
// The following line would not compile, because probe1 no longer has last_reading.
// diagnostic_check(&probe1);
// However we can access name, status and battery_percentage.
println!("Probe name: {}", probe1.name);
println!("Status: {}", probe1.status);
println!("Battery: {}%", probe1.battery_percentage);
}
