How to get a reference to a concrete type from a trait object?2019 Community Moderator ElectionDynamic cast (run-time type inference) in RustIs there a way to convert a trait reference to an object of another unconnected type?How to cast between a trait object and a struct type that implemented the traitConvert between a reference to a trait and a struct that implements that trait in RustHow do I create a polymorphic array and then convert a value to the concrete type?Recovering concrete type of a trait objectBest way to implement union type containerRetrieving generic struct from trait objectHow to match trait implementorsDowncast traits inside Rc for AST manipulationWhat is the difference between self-types and trait subclasses?How to override trait function and call it from the overridden function?References to traits in structsLooking for implementation of the trait core::cmp::PartialEq for intRecovering concrete type of a trait objectRust Trait object conversionVec<T> reference from trait and T lifetimeHow to iterate over a collection of structs as an iterator of trait object references?Specify `Fn` trait bound on struct definition without fixing one of the `Fn` parametersIs there any workaround for converting a Vec of trait objects with marker traits to trait objects without marker traits?
Idiom for feeling after taking risk and someone else being rewarded
Movie: boy escapes the real world and goes to a fantasy world with big furry trolls
Does the US political system, in principle, allow for a no-party system?
Would those living in a "perfect society" not understand satire
Is this Paypal Github SDK reference really a dangerous site?
Smooth vector fields on a surface modulo diffeomorphisms
How is it possible to drive VGA displays at such high pixel clock frequencies?
Difference between `nmap local-IP-address` and `nmap localhost`
Cycles on the torus
Translation of 答えを知っている人はいませんでした
Why restrict private health insurance?
"If + would" conditional in present perfect tense
Rationale to prefer local variables over instance variables?
Did Amazon pay $0 in taxes last year?
Are small insurances worth it?
Short scifi story where reproductive organs are converted to produce "materials", pregnant protagonist is "found fit" to be a mother
How to write a chaotic neutral protagonist and prevent my readers from thinking they are evil?
Can I take the the bonus-action attack from Two-Weapon Fighting without taking the Attack action?
Called into a meeting and told we are being made redundant (laid off) and "not to share outside". Can I tell my partner?
How do I increase the number of TTY consoles?
Why do phishing e-mails use faked e-mail addresses instead of the real one?
What do you call someone who likes to pick fights?
Writing text next to a table
The (Easy) Road to Code
How to get a reference to a concrete type from a trait object?
2019 Community Moderator ElectionDynamic cast (run-time type inference) in RustIs there a way to convert a trait reference to an object of another unconnected type?How to cast between a trait object and a struct type that implemented the traitConvert between a reference to a trait and a struct that implements that trait in RustHow do I create a polymorphic array and then convert a value to the concrete type?Recovering concrete type of a trait objectBest way to implement union type containerRetrieving generic struct from trait objectHow to match trait implementorsDowncast traits inside Rc for AST manipulationWhat is the difference between self-types and trait subclasses?How to override trait function and call it from the overridden function?References to traits in structsLooking for implementation of the trait core::cmp::PartialEq for intRecovering concrete type of a trait objectRust Trait object conversionVec<T> reference from trait and T lifetimeHow to iterate over a collection of structs as an iterator of trait object references?Specify `Fn` trait bound on struct definition without fixing one of the `Fn` parametersIs there any workaround for converting a Vec of trait objects with marker traits to trait objects without marker traits?
How do I get Box<B>
or &B
or &Box<B>
from the a
variable in this code:
trait A
struct B;
impl A for B
fn main()
let mut a: Box<dyn A> = Box::new(B);
let b = a as Box<B>;
This code returns an error:
error[E0605]: non-primitive cast: `std::boxed::Box<dyn A>` as `std::boxed::Box<B>`
--> src/main.rs:8:13
|
8 | let b = a as Box<B>;
| ^^^^^^^^^^^
|
= note: an `as` expression can only be used to convert between primitive types. Consider using the `From` trait
rust traits
add a comment |
How do I get Box<B>
or &B
or &Box<B>
from the a
variable in this code:
trait A
struct B;
impl A for B
fn main()
let mut a: Box<dyn A> = Box::new(B);
let b = a as Box<B>;
This code returns an error:
error[E0605]: non-primitive cast: `std::boxed::Box<dyn A>` as `std::boxed::Box<B>`
--> src/main.rs:8:13
|
8 | let b = a as Box<B>;
| ^^^^^^^^^^^
|
= note: an `as` expression can only be used to convert between primitive types. Consider using the `From` trait
rust traits
add a comment |
How do I get Box<B>
or &B
or &Box<B>
from the a
variable in this code:
trait A
struct B;
impl A for B
fn main()
let mut a: Box<dyn A> = Box::new(B);
let b = a as Box<B>;
This code returns an error:
error[E0605]: non-primitive cast: `std::boxed::Box<dyn A>` as `std::boxed::Box<B>`
--> src/main.rs:8:13
|
8 | let b = a as Box<B>;
| ^^^^^^^^^^^
|
= note: an `as` expression can only be used to convert between primitive types. Consider using the `From` trait
rust traits
How do I get Box<B>
or &B
or &Box<B>
from the a
variable in this code:
trait A
struct B;
impl A for B
fn main()
let mut a: Box<dyn A> = Box::new(B);
let b = a as Box<B>;
This code returns an error:
error[E0605]: non-primitive cast: `std::boxed::Box<dyn A>` as `std::boxed::Box<B>`
--> src/main.rs:8:13
|
8 | let b = a as Box<B>;
| ^^^^^^^^^^^
|
= note: an `as` expression can only be used to convert between primitive types. Consider using the `From` trait
rust traits
rust traits
edited Oct 7 '18 at 19:32
Shepmaster
157k14316457
157k14316457
asked Nov 13 '15 at 7:03
AleksandrAleksandr
32048
32048
add a comment |
add a comment |
2 Answers
2
active
oldest
votes
There are two ways to do downcasting in Rust. The first is to use Any
. Note that this only allows you to downcast to the exact, original concrete type. Like so:
use std::any::Any;
trait A
fn as_any(&self) -> &dyn Any;
struct B;
impl A for B
fn as_any(&self) -> &dyn Any
self
fn main()
let a: Box<dyn A> = Box::new(B);
// The indirection through `as_any` is because using `downcast_ref`
// on `Box<A>` *directly* only lets us downcast back to `&A` again.
// The method ensures we get an `Any` vtable that lets us downcast
// back to the original, concrete type.
let b: &B = match a.as_any().downcast_ref::<B>()
Some(b) => b,
None => panic!("&a isn't a B!"),
;
The other way is to implement a method for each "target" on the base trait (in this case, A
), and implement the casts for each desired target type.
Wait, why do we need as_any
?
Even if you add Any
as a requirement for A
, it's still not going to work correctly. The first problem is that the A
in Box<dyn A>
will also implement Any
... meaning that when you call downcast_ref
, you'll actually be calling it on the object type A
. Any
can only downcast to the type it was invoked on, which in this case is A
, so you'll only be able to cast back down to &dyn A
which you already had.
But there's an implementation of Any
for the underlying type in there somewhere, right? Well, yes, but you can't get at it. Rust doesn't allow you to "cross cast" from &dyn A
to &dyn Any
.
That is what as_any
is for; because it's something only implemented on our "concrete" types, the compiler doesn't get confused as to which one it's supposed to invoke. Calling it on an &dyn A
causes it to dynamically dispatch to the concrete implementation (again, in this case, B::as_any
), which returns an &dyn Any
using the implementation of Any
for B
, which is what we want.
Note that you can side-step this whole problem by just not using A
at all. Specifically, the following will also work:
fn main()
let a: Box<dyn Any> = Box::new(B);
let _: &B = match a.downcast_ref::<B>()
Some(b) => b,
None => panic!("&a isn't a B!")
;
However, this precludes you from having any other methods; all you can do here is downcast to a concrete type.
As a final note of potential interest, the mopa crate allows you to combine the functionality of Any
with a trait of your own.
Yes! I think it fits me. Thanks a lot.
– Aleksandr
Nov 13 '15 at 8:18
I'm talking about the first way :)
– Aleksandr
Nov 13 '15 at 8:31
1
It's worth pointing out why theas_any
function is needed. This is implemented forB
and takes a parameterself
of type&B
, which is converted to a&Any
and can later be cast back to a&B
. Werea.as_any()
to be replaced with(&*a as &Any)
it could only be cast back to the type converted to&Any
, that is&A
.&A
and&B
are not the same thing since they have differing v-tables.
– dhardy
Dec 11 '15 at 20:41
I have been looking for this answer for a full day now. Sometimes Rust feels very counter-intuitive.
– fasih.rana
Oct 5 '17 at 0:46
add a comment |
It should be clear that the cast can fail if there is another type C
implementing A
and you try to cast Box<C>
into a Box<B>
. I don't know your situation, but to me it looks a lot like you are bringing techniques from other languages, like Java, into Rust. I've never encountered this kind of Problem in Rust -- maybe your code design could be improved to avoid this kind of cast.
If you want, you can "cast" pretty much anything with mem::transmute
. Sadly, we will have a problem if we just want to cast Box<A>
to Box<B>
or &A
to &B
because a pointer to a trait
is a fat-pointer that actually consists of two pointers: One to the actual object, one to the vptr. If we're casting it to a struct
type, we can just ignore the vptr. Please remember that this solution is highly unsafe and pretty hacky -- I wouldn't use it in "real" code.
let (b, vptr): (Box<B>, *const ()) = unsafe std::mem::transmute(a) ;
EDIT: Screw that, it's even more unsafe than I thought. If you want to do it correctly this way you'd have to use std::raw::TraitObject
. This is still unstable though. I don't think that this is of any use to OP; don't use it!
There are better alternatives in this very similar question: How to match trait implementors
Thanks for answers. I'm trying to understand how to cope with this situation.So glad to learn about possible solutions.
– Aleksandr
Nov 13 '15 at 8:10
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f33687447%2fhow-to-get-a-reference-to-a-concrete-type-from-a-trait-object%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
There are two ways to do downcasting in Rust. The first is to use Any
. Note that this only allows you to downcast to the exact, original concrete type. Like so:
use std::any::Any;
trait A
fn as_any(&self) -> &dyn Any;
struct B;
impl A for B
fn as_any(&self) -> &dyn Any
self
fn main()
let a: Box<dyn A> = Box::new(B);
// The indirection through `as_any` is because using `downcast_ref`
// on `Box<A>` *directly* only lets us downcast back to `&A` again.
// The method ensures we get an `Any` vtable that lets us downcast
// back to the original, concrete type.
let b: &B = match a.as_any().downcast_ref::<B>()
Some(b) => b,
None => panic!("&a isn't a B!"),
;
The other way is to implement a method for each "target" on the base trait (in this case, A
), and implement the casts for each desired target type.
Wait, why do we need as_any
?
Even if you add Any
as a requirement for A
, it's still not going to work correctly. The first problem is that the A
in Box<dyn A>
will also implement Any
... meaning that when you call downcast_ref
, you'll actually be calling it on the object type A
. Any
can only downcast to the type it was invoked on, which in this case is A
, so you'll only be able to cast back down to &dyn A
which you already had.
But there's an implementation of Any
for the underlying type in there somewhere, right? Well, yes, but you can't get at it. Rust doesn't allow you to "cross cast" from &dyn A
to &dyn Any
.
That is what as_any
is for; because it's something only implemented on our "concrete" types, the compiler doesn't get confused as to which one it's supposed to invoke. Calling it on an &dyn A
causes it to dynamically dispatch to the concrete implementation (again, in this case, B::as_any
), which returns an &dyn Any
using the implementation of Any
for B
, which is what we want.
Note that you can side-step this whole problem by just not using A
at all. Specifically, the following will also work:
fn main()
let a: Box<dyn Any> = Box::new(B);
let _: &B = match a.downcast_ref::<B>()
Some(b) => b,
None => panic!("&a isn't a B!")
;
However, this precludes you from having any other methods; all you can do here is downcast to a concrete type.
As a final note of potential interest, the mopa crate allows you to combine the functionality of Any
with a trait of your own.
Yes! I think it fits me. Thanks a lot.
– Aleksandr
Nov 13 '15 at 8:18
I'm talking about the first way :)
– Aleksandr
Nov 13 '15 at 8:31
1
It's worth pointing out why theas_any
function is needed. This is implemented forB
and takes a parameterself
of type&B
, which is converted to a&Any
and can later be cast back to a&B
. Werea.as_any()
to be replaced with(&*a as &Any)
it could only be cast back to the type converted to&Any
, that is&A
.&A
and&B
are not the same thing since they have differing v-tables.
– dhardy
Dec 11 '15 at 20:41
I have been looking for this answer for a full day now. Sometimes Rust feels very counter-intuitive.
– fasih.rana
Oct 5 '17 at 0:46
add a comment |
There are two ways to do downcasting in Rust. The first is to use Any
. Note that this only allows you to downcast to the exact, original concrete type. Like so:
use std::any::Any;
trait A
fn as_any(&self) -> &dyn Any;
struct B;
impl A for B
fn as_any(&self) -> &dyn Any
self
fn main()
let a: Box<dyn A> = Box::new(B);
// The indirection through `as_any` is because using `downcast_ref`
// on `Box<A>` *directly* only lets us downcast back to `&A` again.
// The method ensures we get an `Any` vtable that lets us downcast
// back to the original, concrete type.
let b: &B = match a.as_any().downcast_ref::<B>()
Some(b) => b,
None => panic!("&a isn't a B!"),
;
The other way is to implement a method for each "target" on the base trait (in this case, A
), and implement the casts for each desired target type.
Wait, why do we need as_any
?
Even if you add Any
as a requirement for A
, it's still not going to work correctly. The first problem is that the A
in Box<dyn A>
will also implement Any
... meaning that when you call downcast_ref
, you'll actually be calling it on the object type A
. Any
can only downcast to the type it was invoked on, which in this case is A
, so you'll only be able to cast back down to &dyn A
which you already had.
But there's an implementation of Any
for the underlying type in there somewhere, right? Well, yes, but you can't get at it. Rust doesn't allow you to "cross cast" from &dyn A
to &dyn Any
.
That is what as_any
is for; because it's something only implemented on our "concrete" types, the compiler doesn't get confused as to which one it's supposed to invoke. Calling it on an &dyn A
causes it to dynamically dispatch to the concrete implementation (again, in this case, B::as_any
), which returns an &dyn Any
using the implementation of Any
for B
, which is what we want.
Note that you can side-step this whole problem by just not using A
at all. Specifically, the following will also work:
fn main()
let a: Box<dyn Any> = Box::new(B);
let _: &B = match a.downcast_ref::<B>()
Some(b) => b,
None => panic!("&a isn't a B!")
;
However, this precludes you from having any other methods; all you can do here is downcast to a concrete type.
As a final note of potential interest, the mopa crate allows you to combine the functionality of Any
with a trait of your own.
Yes! I think it fits me. Thanks a lot.
– Aleksandr
Nov 13 '15 at 8:18
I'm talking about the first way :)
– Aleksandr
Nov 13 '15 at 8:31
1
It's worth pointing out why theas_any
function is needed. This is implemented forB
and takes a parameterself
of type&B
, which is converted to a&Any
and can later be cast back to a&B
. Werea.as_any()
to be replaced with(&*a as &Any)
it could only be cast back to the type converted to&Any
, that is&A
.&A
and&B
are not the same thing since they have differing v-tables.
– dhardy
Dec 11 '15 at 20:41
I have been looking for this answer for a full day now. Sometimes Rust feels very counter-intuitive.
– fasih.rana
Oct 5 '17 at 0:46
add a comment |
There are two ways to do downcasting in Rust. The first is to use Any
. Note that this only allows you to downcast to the exact, original concrete type. Like so:
use std::any::Any;
trait A
fn as_any(&self) -> &dyn Any;
struct B;
impl A for B
fn as_any(&self) -> &dyn Any
self
fn main()
let a: Box<dyn A> = Box::new(B);
// The indirection through `as_any` is because using `downcast_ref`
// on `Box<A>` *directly* only lets us downcast back to `&A` again.
// The method ensures we get an `Any` vtable that lets us downcast
// back to the original, concrete type.
let b: &B = match a.as_any().downcast_ref::<B>()
Some(b) => b,
None => panic!("&a isn't a B!"),
;
The other way is to implement a method for each "target" on the base trait (in this case, A
), and implement the casts for each desired target type.
Wait, why do we need as_any
?
Even if you add Any
as a requirement for A
, it's still not going to work correctly. The first problem is that the A
in Box<dyn A>
will also implement Any
... meaning that when you call downcast_ref
, you'll actually be calling it on the object type A
. Any
can only downcast to the type it was invoked on, which in this case is A
, so you'll only be able to cast back down to &dyn A
which you already had.
But there's an implementation of Any
for the underlying type in there somewhere, right? Well, yes, but you can't get at it. Rust doesn't allow you to "cross cast" from &dyn A
to &dyn Any
.
That is what as_any
is for; because it's something only implemented on our "concrete" types, the compiler doesn't get confused as to which one it's supposed to invoke. Calling it on an &dyn A
causes it to dynamically dispatch to the concrete implementation (again, in this case, B::as_any
), which returns an &dyn Any
using the implementation of Any
for B
, which is what we want.
Note that you can side-step this whole problem by just not using A
at all. Specifically, the following will also work:
fn main()
let a: Box<dyn Any> = Box::new(B);
let _: &B = match a.downcast_ref::<B>()
Some(b) => b,
None => panic!("&a isn't a B!")
;
However, this precludes you from having any other methods; all you can do here is downcast to a concrete type.
As a final note of potential interest, the mopa crate allows you to combine the functionality of Any
with a trait of your own.
There are two ways to do downcasting in Rust. The first is to use Any
. Note that this only allows you to downcast to the exact, original concrete type. Like so:
use std::any::Any;
trait A
fn as_any(&self) -> &dyn Any;
struct B;
impl A for B
fn as_any(&self) -> &dyn Any
self
fn main()
let a: Box<dyn A> = Box::new(B);
// The indirection through `as_any` is because using `downcast_ref`
// on `Box<A>` *directly* only lets us downcast back to `&A` again.
// The method ensures we get an `Any` vtable that lets us downcast
// back to the original, concrete type.
let b: &B = match a.as_any().downcast_ref::<B>()
Some(b) => b,
None => panic!("&a isn't a B!"),
;
The other way is to implement a method for each "target" on the base trait (in this case, A
), and implement the casts for each desired target type.
Wait, why do we need as_any
?
Even if you add Any
as a requirement for A
, it's still not going to work correctly. The first problem is that the A
in Box<dyn A>
will also implement Any
... meaning that when you call downcast_ref
, you'll actually be calling it on the object type A
. Any
can only downcast to the type it was invoked on, which in this case is A
, so you'll only be able to cast back down to &dyn A
which you already had.
But there's an implementation of Any
for the underlying type in there somewhere, right? Well, yes, but you can't get at it. Rust doesn't allow you to "cross cast" from &dyn A
to &dyn Any
.
That is what as_any
is for; because it's something only implemented on our "concrete" types, the compiler doesn't get confused as to which one it's supposed to invoke. Calling it on an &dyn A
causes it to dynamically dispatch to the concrete implementation (again, in this case, B::as_any
), which returns an &dyn Any
using the implementation of Any
for B
, which is what we want.
Note that you can side-step this whole problem by just not using A
at all. Specifically, the following will also work:
fn main()
let a: Box<dyn Any> = Box::new(B);
let _: &B = match a.downcast_ref::<B>()
Some(b) => b,
None => panic!("&a isn't a B!")
;
However, this precludes you from having any other methods; all you can do here is downcast to a concrete type.
As a final note of potential interest, the mopa crate allows you to combine the functionality of Any
with a trait of your own.
edited Sep 11 '18 at 0:50
Shepmaster
157k14316457
157k14316457
answered Nov 13 '15 at 7:53
DK.DK.
35.2k285102
35.2k285102
Yes! I think it fits me. Thanks a lot.
– Aleksandr
Nov 13 '15 at 8:18
I'm talking about the first way :)
– Aleksandr
Nov 13 '15 at 8:31
1
It's worth pointing out why theas_any
function is needed. This is implemented forB
and takes a parameterself
of type&B
, which is converted to a&Any
and can later be cast back to a&B
. Werea.as_any()
to be replaced with(&*a as &Any)
it could only be cast back to the type converted to&Any
, that is&A
.&A
and&B
are not the same thing since they have differing v-tables.
– dhardy
Dec 11 '15 at 20:41
I have been looking for this answer for a full day now. Sometimes Rust feels very counter-intuitive.
– fasih.rana
Oct 5 '17 at 0:46
add a comment |
Yes! I think it fits me. Thanks a lot.
– Aleksandr
Nov 13 '15 at 8:18
I'm talking about the first way :)
– Aleksandr
Nov 13 '15 at 8:31
1
It's worth pointing out why theas_any
function is needed. This is implemented forB
and takes a parameterself
of type&B
, which is converted to a&Any
and can later be cast back to a&B
. Werea.as_any()
to be replaced with(&*a as &Any)
it could only be cast back to the type converted to&Any
, that is&A
.&A
and&B
are not the same thing since they have differing v-tables.
– dhardy
Dec 11 '15 at 20:41
I have been looking for this answer for a full day now. Sometimes Rust feels very counter-intuitive.
– fasih.rana
Oct 5 '17 at 0:46
Yes! I think it fits me. Thanks a lot.
– Aleksandr
Nov 13 '15 at 8:18
Yes! I think it fits me. Thanks a lot.
– Aleksandr
Nov 13 '15 at 8:18
I'm talking about the first way :)
– Aleksandr
Nov 13 '15 at 8:31
I'm talking about the first way :)
– Aleksandr
Nov 13 '15 at 8:31
1
1
It's worth pointing out why the
as_any
function is needed. This is implemented for B
and takes a parameter self
of type &B
, which is converted to a &Any
and can later be cast back to a &B
. Were a.as_any()
to be replaced with (&*a as &Any)
it could only be cast back to the type converted to &Any
, that is &A
. &A
and &B
are not the same thing since they have differing v-tables.– dhardy
Dec 11 '15 at 20:41
It's worth pointing out why the
as_any
function is needed. This is implemented for B
and takes a parameter self
of type &B
, which is converted to a &Any
and can later be cast back to a &B
. Were a.as_any()
to be replaced with (&*a as &Any)
it could only be cast back to the type converted to &Any
, that is &A
. &A
and &B
are not the same thing since they have differing v-tables.– dhardy
Dec 11 '15 at 20:41
I have been looking for this answer for a full day now. Sometimes Rust feels very counter-intuitive.
– fasih.rana
Oct 5 '17 at 0:46
I have been looking for this answer for a full day now. Sometimes Rust feels very counter-intuitive.
– fasih.rana
Oct 5 '17 at 0:46
add a comment |
It should be clear that the cast can fail if there is another type C
implementing A
and you try to cast Box<C>
into a Box<B>
. I don't know your situation, but to me it looks a lot like you are bringing techniques from other languages, like Java, into Rust. I've never encountered this kind of Problem in Rust -- maybe your code design could be improved to avoid this kind of cast.
If you want, you can "cast" pretty much anything with mem::transmute
. Sadly, we will have a problem if we just want to cast Box<A>
to Box<B>
or &A
to &B
because a pointer to a trait
is a fat-pointer that actually consists of two pointers: One to the actual object, one to the vptr. If we're casting it to a struct
type, we can just ignore the vptr. Please remember that this solution is highly unsafe and pretty hacky -- I wouldn't use it in "real" code.
let (b, vptr): (Box<B>, *const ()) = unsafe std::mem::transmute(a) ;
EDIT: Screw that, it's even more unsafe than I thought. If you want to do it correctly this way you'd have to use std::raw::TraitObject
. This is still unstable though. I don't think that this is of any use to OP; don't use it!
There are better alternatives in this very similar question: How to match trait implementors
Thanks for answers. I'm trying to understand how to cope with this situation.So glad to learn about possible solutions.
– Aleksandr
Nov 13 '15 at 8:10
add a comment |
It should be clear that the cast can fail if there is another type C
implementing A
and you try to cast Box<C>
into a Box<B>
. I don't know your situation, but to me it looks a lot like you are bringing techniques from other languages, like Java, into Rust. I've never encountered this kind of Problem in Rust -- maybe your code design could be improved to avoid this kind of cast.
If you want, you can "cast" pretty much anything with mem::transmute
. Sadly, we will have a problem if we just want to cast Box<A>
to Box<B>
or &A
to &B
because a pointer to a trait
is a fat-pointer that actually consists of two pointers: One to the actual object, one to the vptr. If we're casting it to a struct
type, we can just ignore the vptr. Please remember that this solution is highly unsafe and pretty hacky -- I wouldn't use it in "real" code.
let (b, vptr): (Box<B>, *const ()) = unsafe std::mem::transmute(a) ;
EDIT: Screw that, it's even more unsafe than I thought. If you want to do it correctly this way you'd have to use std::raw::TraitObject
. This is still unstable though. I don't think that this is of any use to OP; don't use it!
There are better alternatives in this very similar question: How to match trait implementors
Thanks for answers. I'm trying to understand how to cope with this situation.So glad to learn about possible solutions.
– Aleksandr
Nov 13 '15 at 8:10
add a comment |
It should be clear that the cast can fail if there is another type C
implementing A
and you try to cast Box<C>
into a Box<B>
. I don't know your situation, but to me it looks a lot like you are bringing techniques from other languages, like Java, into Rust. I've never encountered this kind of Problem in Rust -- maybe your code design could be improved to avoid this kind of cast.
If you want, you can "cast" pretty much anything with mem::transmute
. Sadly, we will have a problem if we just want to cast Box<A>
to Box<B>
or &A
to &B
because a pointer to a trait
is a fat-pointer that actually consists of two pointers: One to the actual object, one to the vptr. If we're casting it to a struct
type, we can just ignore the vptr. Please remember that this solution is highly unsafe and pretty hacky -- I wouldn't use it in "real" code.
let (b, vptr): (Box<B>, *const ()) = unsafe std::mem::transmute(a) ;
EDIT: Screw that, it's even more unsafe than I thought. If you want to do it correctly this way you'd have to use std::raw::TraitObject
. This is still unstable though. I don't think that this is of any use to OP; don't use it!
There are better alternatives in this very similar question: How to match trait implementors
It should be clear that the cast can fail if there is another type C
implementing A
and you try to cast Box<C>
into a Box<B>
. I don't know your situation, but to me it looks a lot like you are bringing techniques from other languages, like Java, into Rust. I've never encountered this kind of Problem in Rust -- maybe your code design could be improved to avoid this kind of cast.
If you want, you can "cast" pretty much anything with mem::transmute
. Sadly, we will have a problem if we just want to cast Box<A>
to Box<B>
or &A
to &B
because a pointer to a trait
is a fat-pointer that actually consists of two pointers: One to the actual object, one to the vptr. If we're casting it to a struct
type, we can just ignore the vptr. Please remember that this solution is highly unsafe and pretty hacky -- I wouldn't use it in "real" code.
let (b, vptr): (Box<B>, *const ()) = unsafe std::mem::transmute(a) ;
EDIT: Screw that, it's even more unsafe than I thought. If you want to do it correctly this way you'd have to use std::raw::TraitObject
. This is still unstable though. I don't think that this is of any use to OP; don't use it!
There are better alternatives in this very similar question: How to match trait implementors
edited May 23 '17 at 11:54
Community♦
11
11
answered Nov 13 '15 at 7:55
Lukas KalbertodtLukas Kalbertodt
26.4k257118
26.4k257118
Thanks for answers. I'm trying to understand how to cope with this situation.So glad to learn about possible solutions.
– Aleksandr
Nov 13 '15 at 8:10
add a comment |
Thanks for answers. I'm trying to understand how to cope with this situation.So glad to learn about possible solutions.
– Aleksandr
Nov 13 '15 at 8:10
Thanks for answers. I'm trying to understand how to cope with this situation.So glad to learn about possible solutions.
– Aleksandr
Nov 13 '15 at 8:10
Thanks for answers. I'm trying to understand how to cope with this situation.So glad to learn about possible solutions.
– Aleksandr
Nov 13 '15 at 8:10
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f33687447%2fhow-to-get-a-reference-to-a-concrete-type-from-a-trait-object%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown