How can i define a VariableType with an String

Hello,

i have an function that has an param

pub fn get_value(returnType: String) -> String
let Test: returnType = something;

Yes i can made an if or an match with the String but i hope i have the possibility to made an variable variabletyp.

Rust is a statically-typed language – you’re going to have to be explicit about matching the types you’re interested in here. Or you can use a generic type parameter, with some type constraints that give you the ability to write that “something”, but this still gets resolved at compile time.


pub fn get_value<T>() -> String
where T: Default + Display + Etc
{
    // something
}

@cuviper thx

@cuviper
Can you give me a code for my needings especially, that will be great:

let value: u32 = testmodule.getValue();
let value: String = testmodule.getValue();

testmodule.getValue gets an u32 or an String value back.

pub fn get_value<T>() -> String where T: u32 + String
{
    // something
}

Generics I do not quite get it yet:).

First, if you want to return a value of that generic type, it should be written -> T.

In the T: ... that needs a list of traits which define what you can do with that type T, without even knowing what T is! I gave Default as an example, which would let you create a default u32 (0) or a default String ("") for example.

// alternative: pub fn get_value<T: Default>() -> T
// but sometimes the constraint list is long and complicated
pub fn get_value<T>() -> T
where
    T: Default
{
    // return a new default value.
    // alternatives:
    // Default::default()
    // <T as Default>::default()
    T::default()
}

This function isn’t very useful, since the user could have just called default() on their own, but maybe you have something more complicated in mind with u32 or String. What do you want to return?

@cuviper no i have my hole function ready with a match

pub fn get_value(root: HKEY, key: String, subkey: String, returnType: String) -> String
{
	let root: RegKey = RegKey::predef(root);
	let key: RegKey = root.open_subkey(key).unwrap();
	match returnType.as_ref()
	{
		"u32" =>
		{
			let value: u32 = key.get_value(subkey).unwrap();
			let value: String = value.to_string();
			return value;
		},
		_ =>
		{
			let value: String = "".to_string();
			return value;
		}
	}
} 

Some quirky with match :slight_smile: i think this cannot be the rust-way or? My second problem is must convert the u32 value to a string why rust needs a definitive Type for an return.

1 Like