2
votes

I'm new to Rust and have the following working code. But I don't think what I am doing is the best way. I'm looking for insights about this piece of simple code.

I have a simple struct that holds some data:

struct BlobRef {
    hashname: String,
}

impl BlobRef {
     fn hashname(self) -> String {
         self.hashname
     }
}

And a function call. Don't worry about the source: &[u8], it will have its time to shine.

fn write(bref: BlobRef, source: &[u8]) -> io::Result<String> {
    let hashname = bref.hashname();
    match fs::create_dir_all(&hashname) {
        Ok(_) => Ok(hashname),
        Err(e) => Err(e)
    }
}

I need to assign another scoped variable hashname to stop the compiler complaining about "use of moved variable". Is this idiomatic?

1
try using &self as the parameter of the hashname function instead of selfoli_obk

1 Answers

6
votes

This is not a question whether this is idiomatic or not, I believe; what you need to write depends on what you want to achieve.

Using by-value self and moving String out of the struct, consuming it in process (this is what your example does) is perfectly legitimate thing in certain contexts and wholly depends on your use cases.

On the other hand, if you want only to get the value of the string to read it somewhere (as your example suggests), it is better to return a string slice:

impl BlobRef {
     fn hashname(&self) -> &str {
         &self.hashname
     }
}

Now your second piece code could look like this:

fn write(bref: &BlobRef, source: &[u8]) -> io::Result<String> {
    let hashname = bref.hashname();
    match fs::create_dir_all(hashname) {
        Ok(_) => Ok(hashname.into()),
        Err(e) => Err(e)
    }
}

This require additional allocation in order to get a String out of &str.

However, if the only purpose of BlobRef is to transfer the string to this function, then your original approach is perfectly fine.