【发布时间】:2019-02-16 04:07:32
【问题描述】:
我正在尝试在 Rust 中验证 IP 地址,但我找不到不涉及使用 nightly Rust 的将 str 转换为 u8 的解决方案:
use std::net::{IpAddr, Ipv4Addr};
fn verify_address(address: String) -> bool {
let v: Vec<&str> = address.split('.').collect();
let v_u8: Vec<u8> = v.iter().map(|c| *c.to_owned() as u8).collect();
let addr = IpAddr::V4(Ipv4Addr::new(v_u8[0], v_u8[1], v_u8[2], v_u8[3]));
//.expect("ERR: Error parsing IPv4 address!");
if !addr.is_ipv4() {
return false;
}
return true;
}
error[E0605]: non-primitive cast: `str` as `u8`
--> src/lib.rs:6:42
|
6 | let v_u8: Vec<u8> = v.iter().map(|c| *c.to_owned() as u8).collect();
| ^^^^^^^^^^^^^^^^^^^
|
= note: an `as` expression can only be used to convert between primitive types. Consider using the `From` trait
【问题讨论】:
-
你为什么要尝试cast一个字符串到
u8?难道你不想解析它吗? -
Rust 并没有真正的“原始类型”,与 Java 使用该术语的方式不同。例如,数组、切片、引用、元组、
str和闭包都是原始的。最接近类似于 Java 的“原始类型与引用类型”区别的是Copy与非Copy。
标签: casting rust type-conversion