-
-
Save rust-play/ed63330666eddb34b26ae6f220924ce5 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Cargo.toml dependencies: | |
| // serde = { version = "1.0", features = ["derive"] } | |
| // chrono = "0.4" | |
| // rand_0_8_5 = { package = "rand", version = "0.8.5" } | |
| use serde::Serialize; | |
| use chrono::Utc; | |
| use rand_0_8_5::{thread_rng as rng_legacy, Rng as RngLegacy}; | |
| /// Speed of light in vacuum (m/s) | |
| const SPEED_OF_LIGHT: f64 = 299_792_458.0; | |
| #[derive(Debug, Serialize)] | |
| struct EmissionLine { | |
| element: String, | |
| wavelength_nm: f64, | |
| frequency_thz: f64, | |
| } | |
| impl EmissionLine { | |
| fn from_wavelength(element: &str, nm: f64) -> Self { | |
| // Frequency f = c / lambda | |
| // Convert nm to meters (1e-9) and result to THz (1e-12) | |
| let frequency_hz = SPEED_OF_LIGHT / (nm * 1e-9); | |
| Self { | |
| element: element.to_string(), | |
| wavelength_nm: nm, | |
| frequency_thz: frequency_hz / 1e12, | |
| } | |
| } | |
| } | |
| fn main() { | |
| let now = Utc::now(); | |
| println!("--- Element Spectroscopy Report [{}] ---", now.format("%Y-%m-%d %H:%M:%S")); | |
| // Notable visible emission lines for Titanium (Ti I) in nanometers | |
| let ti_wavelengths = vec![ | |
| 365.35, 399.86, 430.59, 453.32, 498.17, 500.72, 517.37, 519.30, 625.81 | |
| ]; | |
| let mut spectrum: Vec<EmissionLine> = ti_wavelengths | |
| .into_iter() | |
| .map(|wl| EmissionLine::from_wavelength("Titanium", wl)) | |
| .collect(); | |
| // Demonstrate versioned RNG usage from your template | |
| let mut v8 = rng_legacy(); | |
| let noise: f64 = v8.gen_range(-0.01..0.01); | |
| println!("{:<12} | {:<15} | {:<15}", "Element", "Wavelength (nm)", "Frequency (THz)"); | |
| println!("{:-<48}", ""); | |
| for line in &spectrum { | |
| println!( | |
| "{:<12} | {:<15.2} | {:<15.2}", | |
| line.element, | |
| line.wavelength_nm + noise, // Applying slight legacy RNG jitter | |
| line.frequency_thz | |
| ); | |
| } | |
| // Example of serializing the strongest line | |
| if let Ok(json) = serde_json::to_string(&spectrum[0]) { | |
| println!("\nMetadata for strongest line: {}", json); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment