From fc257be1a406f25b33df60584206ab55e404e865 Mon Sep 17 00:00:00 2001 From: qwjyh Date: Tue, 28 Jan 2025 02:53:06 +0900 Subject: [PATCH] minimal example --- .gitignore | 1 + Cargo.lock | 7 ++++++ Cargo.toml | 6 +++++ src/main.rs | 71 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 85 insertions(+) create mode 100644 .gitignore create mode 100644 Cargo.lock create mode 100644 Cargo.toml create mode 100644 src/main.rs diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ea8c4bf --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +/target diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..5facc9d --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,7 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "test-types" +version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..212673e --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "test-types" +version = "0.1.0" +edition = "2021" + +[dependencies] diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..40283d6 --- /dev/null +++ b/src/main.rs @@ -0,0 +1,71 @@ +use std::{fmt::Debug, num::ParseIntError}; + +trait MyTrait { + type Ux: Copy; + type T: Copy + TryFrom + Into + Debug; + + fn val(&self) -> Self::Ux; + + fn converted(&self) -> Self::T + where + <::T as std::convert::TryFrom<::Ux>>::Error: + std::fmt::Debug, + { + self.val().try_into().unwrap() + } +} + +struct MyType1 {} + +impl MyTrait for MyType1 { + type Ux = u32; + + type T = u32; + + fn val(&self) -> Self::Ux { + 10 + } +} + +struct MyType2 {} + +#[derive(Debug, Clone, Copy)] +enum MyType2Val { + A = 0x1, + B = 0x2, +} + +impl Into for MyType2Val { + fn into(self) -> u32 { + self as _ + } +} + +impl TryFrom for MyType2Val { + type Error = ParseIntError; + + fn try_from(value: u32) -> Result { + match value { + 0x1 => Ok(MyType2Val::A), + 0x2 => Ok(MyType2Val::B), + _ => panic!() + } + } +} + +impl MyTrait for MyType2 { + type Ux = u32; + + type T = MyType2Val; + + fn val(&self) -> Self::Ux { + todo!() + } +} + +fn main() { + println!("Hello, world!"); + + let x = MyType1 {}; + println!("{}", x.converted()); +}