[英]How to implement bidirectional conversion with From trait in Rust?
Suppose I have the following type:假设我有以下类型:
#[derive(Default)]
struct Foo(pub i32); // public
Since it's a tuple with a public member, any conversions from/to i32
can simply be made using the 0
member:由于它是一个具有公共成员的元组,因此可以简单地使用
0
成员进行从/到i32
的任何转换:
let foo = Foo::default();
let num: i32 = foo.0; // Foo to i32
let goo = Foo(123); // i32 to Foo
Now I want to make the 0
member non-public, implementing From trait :现在我想让
0
成员不公开,实现From trait :
#[derive(Default)]
struct Foo(i32); // non-public
impl From<i32> for Foo {
fn from(n: i32) -> Foo {
Foo(n)
}
}
But the conversion fails from i32
to Foo
:但是从
i32
到Foo
的转换失败:
let foo = ay::Foo::default();
let num: i32 = foo.into(); // error!
let goo = ay::Foo::from(123); // okay
What's the correct way to implement this bidirectional conversion?实现这种双向转换的正确方法是什么? Rust playground here .
Rust 操场在这里。
You have to implement the other direction ( impl From<Foo> for i32
) manually:您必须手动实现另一个方向(
impl From<Foo> for i32
):
mod x {
#[derive(Default)]
pub struct Foo(i32);
impl From<i32> for Foo {
fn from(n: i32) -> Foo {
Foo(n)
}
}
impl From<Foo> for i32 {
fn from(foo: Foo) -> i32 {
foo.0
}
}
}
fn main() {
let foo = x::Foo::default();
let _num: i32 = foo.into(); // okay
let _goo = x::Foo::from(123); // also okay
}
You can test this in the playground你可以在操场上测试这个
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.