impl From<&str> for Error {
fn from(msg: &str) -> Error {
Error(msg.to_owned())
}
}
impl From<String> for Error {
fn from(msg: String) -> Error {
Error(msg)
}
}
Can I shorten this?pub struct Error(String);
impl From<&str> for Error {
fn from(msg: &str) -> Error {
Error(msg.to_owned())
}
}
impl From<String> for Error {
fn from(msg: String) -> Error {
Error(msg)
}
}
Can I shorten this?format!
Result<(), Error>
I want to be able to write return Err("message".into())
Result<(), String>
because I need to distinguish between different Error
types, e.g. module1::Error
use std::borrow::Cow;
pub struct Error(Cow<'static, str>);
impl From<&'static str> for Error {
fn from(msg: &'static str) -> Error {
Error(Cow::Borrowed(msg))
}
}
impl From<String> for Error {
fn from(msg: String) -> Error {
Error(Cow::Owned(msg))
}
}
fn lol() -> Result<(), Error> {
Err("my error".into())
}
fn lol2() -> Result<(), Error> {
Err(String::from("hello").into())
}
fn main() {}
pub struct Error(String);
impl From<&str> for Error {
fn from(msg: &str) -> Error {
Error(msg.to_owned())
}
}
impl From<String> for Error {
fn from(msg: String) -> Error {
Error(msg)
}
}
Can I shorten this? impl<T: Into<String>> From<T> for Error {
fn from(msg: T) -> Error {
Error(msg.into())
}
}
Not quite sure if the compiler is smart enough to optimize this but it should workimpl<T: Into<String>> From<T> for Error {
fn from(msg: T) -> Error {
Error(msg.into())
}
}
Not quite sure if the compiler is smart enough to optimize this but it should work