Idiomatic Rust: as_FOO vs to_FOO?

In idiomatic Rust naming convention, is to_FOO and as_FOO interchangeable ? If not, what are the rules of thumb for when to use which ?

As seen in std, as_FOO when conversion is cheap, and to_FOO otherwise.
Ex.

// cheap
as_ref
as_ptr
as_str

// potentially expensive 
to_vec
to_string
1 Like

The rust API guidelines has a section on naming conventions for conversion functions: https://rust-lang-nursery.github.io/api-guidelines/naming.html#ad-hoc-conversions-follow-as_-to_-into_-conventions-c-conv

Essentially what @KrishnaSannasi said, though.

2 Likes

@daboross : This definitely contains more information. Thanks!

What does ‘free’ mean in practice? O(1) ?

Yes O(1) and cheap, as in just extracting an encapsulated pointer, like the pointer contained in a Vec or String.

In general, .as_foo() method should takes self as reference (either shared or unique), and returns reference or Copy types. With this rule it’s hard to accidentally write non-cheap code in such method.

2 Likes