Can I use Deref to inherit trait implementations from Other?2019 Community Moderator ElectionHow do you implement deref on a generic type containing a trait in rust?'inheritance' of generic trait implementationImplementing Deref on a struct that owns a boxed traitHow do I print variables in Rust and have it show everything about that variable, like Ruby's .inspect?Rust Trait object conversionCannot infer an appropriate lifetime for lifetime parameter while implementing Deref traitImplementing Deref for a target type held in a CellTrait deref constraintCan a trait give a default implementation for the method of a trait that it inherits from?Store data that implements a trait in a vector
What does "Four-F." mean?
Usage and meaning of "up" in "...worth at least a thousand pounds up in London"
Why is indicated airspeed rather than ground speed used during the takeoff roll?
What is the relationship between relativity and the Doppler effect?
Comment Box for Substitution Method of Integrals
What exactly term 'companion plants' means?
Could Sinn Fein swing any Brexit vote in Parliament?
Print last inputted byte
A Ri-diddley-iley Riddle
Asserting that Atheism and Theism are both faith based positions
Knife as defense against stray dogs
How to get the n-th line after a grepped one?
How are passwords stolen from companies if they only store hashes?
What is the plural TO / OF something
What does Deadpool mean by "left the house in that shirt"?
gerund and noun applications
How could an airship be repaired midflight?
If "dar" means "to give", what does "daros" mean?
Is there a term for accumulated dirt on the outside of your hands and feet?
In the 1924 version of The Thief of Bagdad, no character is named, right?
What is the significance behind "40 days" that often appears in the Bible?
Brake pads destroying wheels
What does "^L" mean in C?
Turning a hard to access nut?
Can I use Deref to inherit trait implementations from Other?
2019 Community Moderator ElectionHow do you implement deref on a generic type containing a trait in rust?'inheritance' of generic trait implementationImplementing Deref on a struct that owns a boxed traitHow do I print variables in Rust and have it show everything about that variable, like Ruby's .inspect?Rust Trait object conversionCannot infer an appropriate lifetime for lifetime parameter while implementing Deref traitImplementing Deref for a target type held in a CellTrait deref constraintCan a trait give a default implementation for the method of a trait that it inherits from?Store data that implements a trait in a vector
I have a String newtype ErrorMessage that I'm using for errors in a prototype crate. (I know that this is a bad practice. I will construct a proper set of distinct error types before publication.)
I need ErrorMessage to implement the Error trait, which is (practically) empty but requires that it also implement the Display and Debug traits, which I have done.
pub struct ErrorMessage(pub String);
impl std::error::Error for ErrorMessage
impl std::fmt::Display for ErrorMessage
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result
self.0.fmt(f)
impl std::fmt::Debug for ErrorMessage
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result
self.0.fmt(f)
This works fine. However, I recently came across Deref and was wondering if it could automatically delegate trait implementations to the implementations for String from self.0.
impl std::ops::Deref for ErrorMessage
type Target = str;
fn deref(&self) -> &str
&self.0
This allows me to call methods like .to_string() on an ErrorMessage, and deref coercion will let it use my Deref implementation to automatically find the fmt and to_string implementations on self.0/*self.
However, ErrorMessage itself isn't actually Display or Debug. If I try to println! or format! an instance directly I get an error, and it doesn't satisfy the bounds for Error.
fn main() -> Result<(), ErrorMessage>
Err(ErrorMessage("hello world".to_string()))
error[E0277]: `ErrorMessage` doesn't implement `std::fmt::Display`
--> src/main.rs:2:6
|
2 | impl std::error::Error for ErrorMessage
| ^^^^^^^^^^^^^^^^^ `ErrorMessage` cannot be formatted with the default formatter
|
= help: the trait `std::fmt::Display` is not implemented for `ErrorMessage`
Is there any way to use Deref, DerefMut, or something similar to allow dereffed values to satisfy trait bounds for the original values. I'm looking for somethinig automatic, as an alternative to manually writing impl blocks to delegate each of them.
I recognize that this is probably also a bad idea in practice. This is just hypothetical.
rust
add a comment |
I have a String newtype ErrorMessage that I'm using for errors in a prototype crate. (I know that this is a bad practice. I will construct a proper set of distinct error types before publication.)
I need ErrorMessage to implement the Error trait, which is (practically) empty but requires that it also implement the Display and Debug traits, which I have done.
pub struct ErrorMessage(pub String);
impl std::error::Error for ErrorMessage
impl std::fmt::Display for ErrorMessage
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result
self.0.fmt(f)
impl std::fmt::Debug for ErrorMessage
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result
self.0.fmt(f)
This works fine. However, I recently came across Deref and was wondering if it could automatically delegate trait implementations to the implementations for String from self.0.
impl std::ops::Deref for ErrorMessage
type Target = str;
fn deref(&self) -> &str
&self.0
This allows me to call methods like .to_string() on an ErrorMessage, and deref coercion will let it use my Deref implementation to automatically find the fmt and to_string implementations on self.0/*self.
However, ErrorMessage itself isn't actually Display or Debug. If I try to println! or format! an instance directly I get an error, and it doesn't satisfy the bounds for Error.
fn main() -> Result<(), ErrorMessage>
Err(ErrorMessage("hello world".to_string()))
error[E0277]: `ErrorMessage` doesn't implement `std::fmt::Display`
--> src/main.rs:2:6
|
2 | impl std::error::Error for ErrorMessage
| ^^^^^^^^^^^^^^^^^ `ErrorMessage` cannot be formatted with the default formatter
|
= help: the trait `std::fmt::Display` is not implemented for `ErrorMessage`
Is there any way to use Deref, DerefMut, or something similar to allow dereffed values to satisfy trait bounds for the original values. I'm looking for somethinig automatic, as an alternative to manually writing impl blocks to delegate each of them.
I recognize that this is probably also a bad idea in practice. This is just hypothetical.
rust
Note that your code does work if you fix the deref implementation (see play.rust-lang.org/…)
– aochagavia
Mar 7 at 8:57
you can derive Debug for ErrorMessage, but Display should still be implemented manually
– Laney
Mar 7 at 10:29
@aochagavia Thanks for the correction! I've fixed the deref definition and updated my sandbox examples. Unfortunately that still doesn't let me get rid of theimpl Debugandimpl Displayblocks.
– Jackie
Mar 7 at 17:56
You cannot inherit trait implementations, but for common traits you can use the derive_more crate. Does this answer your question? If yes, I can post it as an answer.
– aochagavia
Mar 12 at 10:14
@aochagavia Thanks for the suggestion, that's good to know! but it's not quite what I'm looking for.
– Jackie
yesterday
add a comment |
I have a String newtype ErrorMessage that I'm using for errors in a prototype crate. (I know that this is a bad practice. I will construct a proper set of distinct error types before publication.)
I need ErrorMessage to implement the Error trait, which is (practically) empty but requires that it also implement the Display and Debug traits, which I have done.
pub struct ErrorMessage(pub String);
impl std::error::Error for ErrorMessage
impl std::fmt::Display for ErrorMessage
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result
self.0.fmt(f)
impl std::fmt::Debug for ErrorMessage
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result
self.0.fmt(f)
This works fine. However, I recently came across Deref and was wondering if it could automatically delegate trait implementations to the implementations for String from self.0.
impl std::ops::Deref for ErrorMessage
type Target = str;
fn deref(&self) -> &str
&self.0
This allows me to call methods like .to_string() on an ErrorMessage, and deref coercion will let it use my Deref implementation to automatically find the fmt and to_string implementations on self.0/*self.
However, ErrorMessage itself isn't actually Display or Debug. If I try to println! or format! an instance directly I get an error, and it doesn't satisfy the bounds for Error.
fn main() -> Result<(), ErrorMessage>
Err(ErrorMessage("hello world".to_string()))
error[E0277]: `ErrorMessage` doesn't implement `std::fmt::Display`
--> src/main.rs:2:6
|
2 | impl std::error::Error for ErrorMessage
| ^^^^^^^^^^^^^^^^^ `ErrorMessage` cannot be formatted with the default formatter
|
= help: the trait `std::fmt::Display` is not implemented for `ErrorMessage`
Is there any way to use Deref, DerefMut, or something similar to allow dereffed values to satisfy trait bounds for the original values. I'm looking for somethinig automatic, as an alternative to manually writing impl blocks to delegate each of them.
I recognize that this is probably also a bad idea in practice. This is just hypothetical.
rust
I have a String newtype ErrorMessage that I'm using for errors in a prototype crate. (I know that this is a bad practice. I will construct a proper set of distinct error types before publication.)
I need ErrorMessage to implement the Error trait, which is (practically) empty but requires that it also implement the Display and Debug traits, which I have done.
pub struct ErrorMessage(pub String);
impl std::error::Error for ErrorMessage
impl std::fmt::Display for ErrorMessage
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result
self.0.fmt(f)
impl std::fmt::Debug for ErrorMessage
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result
self.0.fmt(f)
This works fine. However, I recently came across Deref and was wondering if it could automatically delegate trait implementations to the implementations for String from self.0.
impl std::ops::Deref for ErrorMessage
type Target = str;
fn deref(&self) -> &str
&self.0
This allows me to call methods like .to_string() on an ErrorMessage, and deref coercion will let it use my Deref implementation to automatically find the fmt and to_string implementations on self.0/*self.
However, ErrorMessage itself isn't actually Display or Debug. If I try to println! or format! an instance directly I get an error, and it doesn't satisfy the bounds for Error.
fn main() -> Result<(), ErrorMessage>
Err(ErrorMessage("hello world".to_string()))
error[E0277]: `ErrorMessage` doesn't implement `std::fmt::Display`
--> src/main.rs:2:6
|
2 | impl std::error::Error for ErrorMessage
| ^^^^^^^^^^^^^^^^^ `ErrorMessage` cannot be formatted with the default formatter
|
= help: the trait `std::fmt::Display` is not implemented for `ErrorMessage`
Is there any way to use Deref, DerefMut, or something similar to allow dereffed values to satisfy trait bounds for the original values. I'm looking for somethinig automatic, as an alternative to manually writing impl blocks to delegate each of them.
I recognize that this is probably also a bad idea in practice. This is just hypothetical.
rust
rust
edited Mar 7 at 17:55
Jackie
asked Mar 6 at 21:41
JackieJackie
164
164
Note that your code does work if you fix the deref implementation (see play.rust-lang.org/…)
– aochagavia
Mar 7 at 8:57
you can derive Debug for ErrorMessage, but Display should still be implemented manually
– Laney
Mar 7 at 10:29
@aochagavia Thanks for the correction! I've fixed the deref definition and updated my sandbox examples. Unfortunately that still doesn't let me get rid of theimpl Debugandimpl Displayblocks.
– Jackie
Mar 7 at 17:56
You cannot inherit trait implementations, but for common traits you can use the derive_more crate. Does this answer your question? If yes, I can post it as an answer.
– aochagavia
Mar 12 at 10:14
@aochagavia Thanks for the suggestion, that's good to know! but it's not quite what I'm looking for.
– Jackie
yesterday
add a comment |
Note that your code does work if you fix the deref implementation (see play.rust-lang.org/…)
– aochagavia
Mar 7 at 8:57
you can derive Debug for ErrorMessage, but Display should still be implemented manually
– Laney
Mar 7 at 10:29
@aochagavia Thanks for the correction! I've fixed the deref definition and updated my sandbox examples. Unfortunately that still doesn't let me get rid of theimpl Debugandimpl Displayblocks.
– Jackie
Mar 7 at 17:56
You cannot inherit trait implementations, but for common traits you can use the derive_more crate. Does this answer your question? If yes, I can post it as an answer.
– aochagavia
Mar 12 at 10:14
@aochagavia Thanks for the suggestion, that's good to know! but it's not quite what I'm looking for.
– Jackie
yesterday
Note that your code does work if you fix the deref implementation (see play.rust-lang.org/…)
– aochagavia
Mar 7 at 8:57
Note that your code does work if you fix the deref implementation (see play.rust-lang.org/…)
– aochagavia
Mar 7 at 8:57
you can derive Debug for ErrorMessage, but Display should still be implemented manually
– Laney
Mar 7 at 10:29
you can derive Debug for ErrorMessage, but Display should still be implemented manually
– Laney
Mar 7 at 10:29
@aochagavia Thanks for the correction! I've fixed the deref definition and updated my sandbox examples. Unfortunately that still doesn't let me get rid of the
impl Debug and impl Display blocks.– Jackie
Mar 7 at 17:56
@aochagavia Thanks for the correction! I've fixed the deref definition and updated my sandbox examples. Unfortunately that still doesn't let me get rid of the
impl Debug and impl Display blocks.– Jackie
Mar 7 at 17:56
You cannot inherit trait implementations, but for common traits you can use the derive_more crate. Does this answer your question? If yes, I can post it as an answer.
– aochagavia
Mar 12 at 10:14
You cannot inherit trait implementations, but for common traits you can use the derive_more crate. Does this answer your question? If yes, I can post it as an answer.
– aochagavia
Mar 12 at 10:14
@aochagavia Thanks for the suggestion, that's good to know! but it's not quite what I'm looking for.
– Jackie
yesterday
@aochagavia Thanks for the suggestion, that's good to know! but it's not quite what I'm looking for.
– Jackie
yesterday
add a comment |
0
active
oldest
votes
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%2f55032618%2fcan-i-use-dereftarget-other-to-inherit-trait-implementations-from-other%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
0
active
oldest
votes
0
active
oldest
votes
active
oldest
votes
active
oldest
votes
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%2f55032618%2fcan-i-use-dereftarget-other-to-inherit-trait-implementations-from-other%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
Note that your code does work if you fix the deref implementation (see play.rust-lang.org/…)
– aochagavia
Mar 7 at 8:57
you can derive Debug for ErrorMessage, but Display should still be implemented manually
– Laney
Mar 7 at 10:29
@aochagavia Thanks for the correction! I've fixed the deref definition and updated my sandbox examples. Unfortunately that still doesn't let me get rid of the
impl Debugandimpl Displayblocks.– Jackie
Mar 7 at 17:56
You cannot inherit trait implementations, but for common traits you can use the derive_more crate. Does this answer your question? If yes, I can post it as an answer.
– aochagavia
Mar 12 at 10:14
@aochagavia Thanks for the suggestion, that's good to know! but it's not quite what I'm looking for.
– Jackie
yesterday