gpt4 book ai didi

rust - 信任:隐式地从usize转换为相应的int类型

转载 作者:行者123 更新时间:2023-12-03 11:40:58 32 4
gpt4 key购买 nike

我想知道是否有人有解决方案允许从usize类型(从访问数组索引或获取矢量长度中获得)的隐式转换为i32?可能吗?
当然,我假设矢量长度和数组范围在i32限制之内。

最佳答案

您可以在函数参数中使用 TryInto 特性从调用者的角度进行隐式转换。它仍然涉及转换,但是它将复杂性移到了要调用的函数上:

use std::convert::TryInto;

fn stuff(val: impl TryInto<i32>) {
// use try_into trait method
let val = match val.try_into() {
Ok(v) => v,
Err(_) => panic!("couldn't fit in i32"),
};
println!("in stuff: val has {} leading zeros", val.leading_zeros());
}

fn main() {
let letters = ['a', 'b', 'c'];
let len = letters.len();
println!("in main: len has {} leading zeros", len.leading_zeros());
stuff(len); // implict conversion
}
输出
in main: len has 62 leading zeros
in stuff: val has 30 leading zeros
Try on the playground

关于rust - 信任:隐式地从usize转换为相应的int类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66588391/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com