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()
`as_bytes()gives a
` gives a &[u8]
`&[u8]view into a
` view into a &str
`&str`, which is a no-op.to_owned()
`to_owned()copies a
` copies a &str
`&strto a new
` to a new String
`String`.into_bytes()
`into_bytes()consumes a
` consumes a String
`Stringand yields the underlying
` and yields the underlying
Vec<u8>
`VecConversions prefixed as_
`as_and
` and into_
`into_typically _decrease abstraction_, either exposing a view into the underlying representation (
` typically decrease abstraction, either
exposing a view into the underlying representation (as
`as) or deconstructing data into its underlying representation (
`) or deconstructing data
into its underlying representation (into
`into). Conversions prefixed
`). Conversions prefixed to_
`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?