Rust——结构体泛型
结构体泛型
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | #[derive(Debug)] struct Color<T>{ //定义泛型数组Color chanel1:T, chanel2:T, chanel3:T, } //泛型结构体关联函数 impl<T> Color<T>{ fn create(chanel1:T,chanel2:T,chanel3:T)->Color<T>{ Color{ chanel1,chanel2,chanel3 } } } fn main(){ //定义浮点型颜色通道坐标值0.0-255.0 let f_color = Color::create(0f32,0f32,0f32); println!( "浮点型表示颜色三通道值 {:#?}" ,f_color); let hex_color = Color::create(0x10,0x10,0x10); println!( "整型表示颜色三通道值 {:#?}" ,hex_color); } |
运行结果:
若将以上代码中一句更改如下:
1 | let f_color = Color::create(0f32,0f32,0f64); |
运行后报错如下:
以上报错的原因是因为三个通道的值类型要一致(第3通道值为f64,前两个通道值为f32)
若要定义的三个通道的值可以取不同数据类型,可如下操作:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | #[derive(Debug)] struct Colors<C1,C2,C3>{ chanel1:C1, chanel2:C2, chanel3:C3, } impl<C1,C2,C3> Colors<C1,C2,C3>{ fn create(chanel1:C1,chanel2:C2,chanel3:C3)->Colors<C1,C2,C3>{ Colors{ chanel1,chanel2,chanel3 } } } #[derive(Debug)] struct Color<T>{ //定义泛型数组Color,带入参数需同种数据类型 chanel1:T, chanel2:T, chanel3:T, } //泛型结构体关联函数 impl<T> Color<T>{ fn create(chanel1:T,chanel2:T,chanel3:T)->Color<T>{ Color{ chanel1,chanel2,chanel3 } } } fn main(){ //定义浮点型颜色通道坐标值0.0-255.0 let f_color = Color::create(0f32,0f32,0f32); println!( "浮点型表示颜色三通道值 {:#?}" ,f_color); let hex_color = Color::create(0x10,0x10,0x10); println!( "整型表示颜色三通道值 {:#?}" ,hex_color); let varis_color = Colors::create(12u32,0f32,90i32); println!( "多数据类型表示颜色三通道{:#?}" ,varis_color); } |
运行后结果如下:
------------------------------------
承接
**视觉检测软件开发及调试
**工业软件开发
**上位机软件开发
wechat:luoran2024
qq:565934058
email:taoyuansu@qq.com
海量教育资源及影视资源下载
微信公众号:EFun科技
------------------------------------
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 没有源码,如何修改代码逻辑?
· PowerShell开发游戏 · 打蜜蜂
· 在鹅厂做java开发是什么体验
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战