try_into Guards Narrowing Conversions
Route narrowing numeric conversions through try_into so out-of-range values return TryFromIntError instead of silently truncating bits.
Code
use std::convert::TryInto;
fn main() {
let wide: i64 = 300;
// try_into:目标装得下才成功,越界返回 Err 而不是截断位模式
match wide.try_into() {
Ok(small) => println!("300 fits u8: {small}"),
Err(e) => println!("300 does not fit u8: {e}"),
}
let negative: i64 = -1;
match negative.try_into() {
Ok(_) => println!("-1 accepted as u8"),
Err(e) => println!("-1 rejected as u8: {e}"),
}
// 边界值恰好可达:i64::MAX 转 u64 成功,负数则失败
let ok: Result<u64, _> = i64::MAX.try_into();
println!("i64::MAX -> u64 ok: {}", ok.is_ok());
// 无损方向编译期就有把握:u8 -> i16 直接 From,无需 Result
let byte: u8 = 200;
let widened: i16 = byte.into();
println!("widened: {widened}");
// 端口解析这类边界校验的标准写法
let raw: u32 = 80_000;
let port: Result<u16, _> = raw.try_into();
println!("port 80000 valid: {}", port.is_ok());
}Inside the snippet
Under the hood: the function main.
Result is the error channel: the caller receives the failure as a value instead of an exception. Pattern matching via match forces each shape of the value to be handled.
What to watch for
- It carries its own context — no imports beyond the runtime’s own surface.
Resultis the only error channel — remove a?while adapting and that site needs an explicitmatch.
Putting it to use
Entry signature: fn main()
The run emits 7 labeled sections — 300 fits u8:, 300 does not fit u8:, -1 accepted as u8, -1 rejected as u8:, i64::MAX -> u64 ok:, widened:, port 80000 valid: — one per step.
The core lines, annotated
match negative.try_into() {
Ok(_) => println!("-1 accepted as u8"),
Err(e) => println!("-1 rejected as u8: {e}"),
}
match wide.try_into() {
Ok(small) => println!("300 fits u8: {small}"),
Err(e) => println!("300 does not fit u8: {e}"),
}
Interactive Tools for This Topic
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.A/B Test Sample Size CalculatorCalculate required per-variant sample size and experiment duration for two-proportion A/B tests from baseline conversion, MDE, alpha, and statistical power.
FAQ
- How are errors reported?
- Each fallible operation returns `Result`; nothing is silently discarded.
- What does try_into Guards Narrowing Conversions print when run?
- Run it as a complete program — the output lines carry labels such as `300 fits u8:`, `300 does not fit u8:`, `-1 accepted as u8`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.