Putting a Default bound on T is the idiomatic way to construct generic types within a generic function.
There's nothing special about the Default trait though and you can declare a similar trait and use that within your generic functions.
Also, if a type implements Copy or Clone you can initialize as many copies and clones as you want from a single value.
Commented examples:
// use Default bound to call default() on generic type
fn func_default<T: Default>() -> T {
T::default()
}
// note: there's nothing special about the Default trait
// you can implement your own trait identical to it
// and use it in the same way in generic functions
trait CustomTrait {
fn create() -> Self;
}
impl CustomTrait for String {
fn create() -> Self {
String::from("I'm a custom initialized String")
}
}
// use CustomTrait bound to call create() on generic type
fn custom_trait<T: CustomTrait>() -> T {
T::create()
}
// can multiply copyable types
fn copyable<T: Copy>(t: T) -> (T, T) {
(t, t)
}
// can also multiply cloneable types
fn cloneable<T: Clone>(t: T) -> (T, T) {
(t.clone(), t)
}
playground
Default, what would you want it to initialize to?Defaultbound onTand initialize the generic type withT::default(). If you're willing to use unsafe code then you can look up the implementation forrotate_rightwithin the Rust standard library, or just userotate_rightdirectly.rotate_rightis in the standard library, and you can read the code for it -- it just usesunsafe(although admittedly not in exactly the way you refer to). What makes you think there needs to be another way? Or why do the two options you've ruled out not satisfy your requirements?rotate_rightnecessarily, but that the question already contained two reasonable answers and seemed to be asking for "anything else?" without any real parameters on the solution. Since the edits the question no longer has this problem; I've revoked my close vote.