Skip to content

Instantly share code, notes, and snippets.

@dacr
Created October 16, 2024 19:54
Show Gist options
  • Save dacr/1c530df766657844288e5673c8910d45 to your computer and use it in GitHub Desktop.
Save dacr/1c530df766657844288e5673c8910d45 to your computer and use it in GitHub Desktop.
hello rust type conversions / published by https://github.com/dacr/code-examples-manager #78987a3a-c3e9-401e-bdf6-773c55c6f3fb/ce934c8b84360787a90cdb76a2889e52608db41d
#!/usr/bin/env rust-script
// summary : hello rust type conversions
// keywords : rust, types, conversions, @testable
// publish : gist
// authors : David Crosson
// license : Apache NON-AI License Version 2.0 (https://raw.githubusercontent.com/non-ai-licenses/non-ai-licenses/main/NON-AI-APACHE2)
// id : 78987a3a-c3e9-401e-bdf6-773c55c6f3fb
// created-on : 2024-10-16T09:27:59+02:00
// managed-by : https://github.com/dacr/code-examples-manager
// run-with : ./$file
#[derive(Debug, PartialEq, Clone)]
struct BigPoint {
x: f64,
y: f64,
}
impl From<(f64, f64)> for BigPoint {
fn from(value: (f64, f64)) -> Self {
Self { x: value.0, y: value.1 }
}
}
impl From<BigPoint> for (f64, f64) {
fn from(value: BigPoint) -> (f64, f64) {
(value.x, value.y)
}
}
fn main() {
let p = BigPoint::from((1.2, 3.4)); // CONVERSION FROM TUPLE TO BigPoint
assert_eq!(p, BigPoint { x: 1.2, y: 3.4 });
let p: BigPoint = (0.1, 1.1).into(); // CONVERSION FROM TUPLE TO BigPoint
assert_eq!(p, BigPoint { x: 0.1, y: 1.1 });
let t: (f64, f64) = p.clone().into(); // CONVERSION FROM BigPoint to TUPLE
println!("{:?}, {:?}", p, t);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment