Rust - When to use as_ vs to_ vs into_

Viewed 113

My understanding, based on the standard library examples, is that:

into_ convention is used when the function completely absorbs the ownership and spits out another type, as in into_iter() . Is the understanding correct?

The real confusion is between as_ and to_ .
It seems to_ as in to_owned() takes the reference of a type and spits a new related type (like a type coercion), where as to_string() takes the reference of type and spits a new type (as in type conversion).

But as_ as in as_ptr also seems like type coercion. I couldn't find any examples for this beyond as_ptr or as_mut.

Can someone explain exactly the cases where we need to use the specific naming convention and with a real life example that is beyond what's used in standard library?

0 Answers
Related