minimal example
This commit is contained in:
commit
fc257be1a4
4 changed files with 85 additions and 0 deletions
1
.gitignore
vendored
Normal file
1
.gitignore
vendored
Normal file
|
@ -0,0 +1 @@
|
||||||
|
/target
|
7
Cargo.lock
generated
Normal file
7
Cargo.lock
generated
Normal file
|
@ -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"
|
6
Cargo.toml
Normal file
6
Cargo.toml
Normal file
|
@ -0,0 +1,6 @@
|
||||||
|
[package]
|
||||||
|
name = "test-types"
|
||||||
|
version = "0.1.0"
|
||||||
|
edition = "2021"
|
||||||
|
|
||||||
|
[dependencies]
|
71
src/main.rs
Normal file
71
src/main.rs
Normal file
|
@ -0,0 +1,71 @@
|
||||||
|
use std::{fmt::Debug, num::ParseIntError};
|
||||||
|
|
||||||
|
trait MyTrait {
|
||||||
|
type Ux: Copy;
|
||||||
|
type T: Copy + TryFrom<Self::Ux> + Into<Self::Ux> + Debug;
|
||||||
|
|
||||||
|
fn val(&self) -> Self::Ux;
|
||||||
|
|
||||||
|
fn converted(&self) -> Self::T
|
||||||
|
where
|
||||||
|
<<Self as MyTrait>::T as std::convert::TryFrom<<Self as MyTrait>::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<u32> for MyType2Val {
|
||||||
|
fn into(self) -> u32 {
|
||||||
|
self as _
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TryFrom<u32> for MyType2Val {
|
||||||
|
type Error = ParseIntError;
|
||||||
|
|
||||||
|
fn try_from(value: u32) -> Result<Self, Self::Error> {
|
||||||
|
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());
|
||||||
|
}
|
Loading…
Reference in a new issue