Short answer: You can't. That's because digest()
returns an owned value and as_ref()
(by definition) borrows from it. When the function returns, the memory owned by the return value of digest()
is destroyed and the referenced returned by as_ref()
becomes invalid.
I guess your goal is to hide the implementation detail that digest()
returns a GenericArray
, while you only need a &[u8]
. You can get something similar by hiding the concrete type:
fn sha512_256_digest(str: &[u8]) -> impl AsRef<[u8]> {
digest::digest(&digest::SHA512_256, str)
}
... should work. The function signature says that the return value will be some anonymous type which the caller can only ever know about that it can be referenced as if it was a &[u8]
. The caller can do
// `d` is of some anonymous type
let d = sha512_256_digest(...);
// `db` is a &[u8]
let db = d.as_ref();
However, I'd recommend not to hide types in such a way.