Is it bad practice to implement From<&str> instead of FromStr?

Hi,
Should I implement FromStr and parse() the value instead of implementing From<&str>?
In general is it considered bad practice to implement From<&str>?

It entirely depends on whether the conversion is lossless. If it can fail, implement FromStr only. If it always succeeds, implement From<&str> and you can also implement FromStr with Err = Infallible.

1 Like

Thanks!
And how about implementing TryFrom<&str> instead of FromStr?

I wouldn't recommend doing it instead, because you then lose .parse() sugar. But you can do both.

4 Likes

Take a look at the standard library for inspiration.

  • From<&str> is implemented in order to box a string slice, or to copy the string into an owned buffer like String, OsString or Vec<u8>.
  • FromStr is implemented when a type has a string representation but is not itself a string, and needs to be parsed. It's also implemented for a few string types with infallible allocating conversions: String, OsString, PathBuf.
  • TryFrom<&str> is not implemented.

From<&str> implementors

Arc<str>
Box<dyn Error>
Box<dyn Error + Send + Sync>
Box<str>
Cow<str>
OsString
Rc<str>
String
Vec<u8>

FromStr implementors

bool
char
f32
f64
i8
i16
i32
i64
i128
IpAddr
Ipv4Addr
Ipv6Addr
isize
Literal
NonZeroI8
NonZeroI16
NonZeroI32
NonZeroI64
NonZeroI128
NonZeroIsize
NonZeroU8
NonZeroU16
NonZeroU32
NonZeroU64
NonZeroU128
NonZeroUsize
OsString
PathBuf
SocketAddr
SocketAddrV4
SocketAddrV6
String
TokenStream
u8
u16
u32
u64
u128
usize

TryFrom<&str> implementors

None.

4 Likes

Also, a few things in the ecosystem rely on the FromStr trait. Like clap derive API.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.