72 lines
2.6 KiB

use std::path::Path;
fn main() {
#[derive(Copy, Clone, Debug)]
struct CopyObject<'a> {
pub val: &'a str,
struct AnObject {
pub val: String,
struct TheOtherObject {
pub val: Vec<u8>,
impl AnObject {
// as_ borrowed (&self) -> borrowed (&[u8])
fn as_bytes(&self) -> &[u8] {
// because the underlying data structure of a String is a Vec<u8>, the as_bytes actually just returns this as a borrowed value, really just making this a dumb proxy, but it shows us what we want: as_ is just a view into the underlying data structure: nothing is copied, nothing new is created, it only exposes the underlying data: free as in free beer because we are just returning something that point to something else: a reference
// to_ borrowed (&self) -> borrowed (&[u8])
fn to_guarded_bytes(&self) -> Option<&[u8]> {
// this is really a dumb example, but it kind of proves the point: we convert our Target to a str. The input and output smells like the above as_ and the as_ is free, but this really isn't, because we are doing some expensive validation first
let mut is_valid = true;
for s in self.val.chars() {
if s > 'b' && s < 'w' {
is_valid = false;
if is_valid {
return Some(self.val.as_bytes());
// to_ borrowed (&self) -> owned (TheOtherObject) (non-copy types)
fn to_guarded_object(&self) -> Option<TheOtherObject> {
// This performs our previous check, and if everything is fine, it converts our object to the new object, simply creating it, and making some more to_ calls. Really expensive, but no copy is made of `self`
let guarded_bytes = self.to_guarded_bytes();
match guarded_bytes {
Some(bytes) => {
Some(TheOtherObject {val: bytes.to_vec()})
None => None
impl<'a> CopyObject<'a> {
// to_ owned (self) -> owned (TheOtherObject) (copy types)
fn to_object(self) -> TheOtherObject {
// because self is not a reference, it is actually not consumed (likewise it isn't consumed when we do a &self ... yes we could do a &self here, but it kind of defeats the purpose of doing the example), but it is copied. The copy itself though is more expensive than just doing a reference. In our example, we are actually being quite expensive doing a to_vec conversion of our free as_ view
TheOtherObject { val: self.val.as_bytes().to_vec()}
// into_ owned -> owned (non-copy types)