我想在Rust中构建一个类,该类允许在其实例化中具有多样性和方便性,类似于std::net::TcpStream
可以为其connect
方法提供多个输入的方式。如何创建一个具有多个实例化选项的类
我有以下的测试,但我需要建立实现这一结果的结构或特征的很少的想法。
#[cfg(test)]
mod test {
use super::Ipv4Network;
use std::net::Ipv4Addr;
#[test]
fn instantiation() {
let net_addr = Ipv4Addr::new(10, 0, 0, 0);
let net_mask = Ipv4Addr::new(255, 255, 255, 240);
// Instantiate an Ipv4Network using two Ipv4Addrs.
let with_addrs = Ipv4Network::new(net_addr, net_mask);
// Instantiate an Ipv4Network using an Ipv4Addr and a prefix integer.
let with_addr_prefix = Ipv4Network::new(net_addr, 28);
// Instantiate an Ipv4Network using two strings.
let with_strings = Ipv4Network::new("10.0.0.0", "255.255.255.240");
// Instantiate an Ipv4Network using a string and a prefix integer.
let with_prefix = Ipv4Network::new("10.0.0.0", 28);
// Instantiate an Ipv4Network using a string with CIDR notation.
let with_cidr = Ipv4Network::new("10.0.0.0/28");
}
}
我的理解是std::net::TcpStream
通过ToSocketAddrs性状来实现其多种connect
输入,其源极可以发现here。究竟如何std::net:TcpStream::connect
uses ToSocketAddrs是我也不清楚,但我想我应该能够定义一个Ipv4Network
如下:
pub struct Ipv4Network {
addr: Ipv4Addr,
mask: Ipv4Addr,
}
如果这是真的,那么我该如何去创造一个特质(比如ToIpv4Network
),其功能像ToSocketAddrs
的确为std::net:TcpStream
?
什么都要的
impl ToIpv4Network for (Ipv4Addr, Ipv4Addr) {
...
}
样子的肉吗?这是否正确的道路开始下降?