The guidelines below were approved by rust issue #7087.
[FIXME] Should we provide standard traits for conversions? Doing so nicely will require trait reform to land.
Conversions should be provided as methods, with names prefixed as follows:
Prefix | Cost | Consumes convertee |
---|---|---|
as_ `as_` |
Free | No |
to_ `to_` |
Expensive | No |
into_ `into_` |
Variable | Yes |
For example:
as_bytes()
gives a &[u8]
`&[u8]view into a
&str`, which is a no-op.to_owned()
copies a &str
`&strto a new
` to a new String
`String`.into_bytes()
consumes a String
`Stringand yields the underlying
VecConversions prefixed as_
`as_and
` and into_
`into_typically _decrease abstraction_, either exposing a view into the underlying representation (
as) or deconstructing data into its underlying representation (
into). Conversions prefixed
to_`, on the
other hand, typically stay at the same level of abstraction but do some work to
change one representation into another.
[FIXME] The distinctions between conversion methods does not work so well for
from_
`from_` conversion constructors. Is that a problem?