This code returns a pointer, for example 0x625f02281b50play
fn foo (data: &String) -> Result<*const u8, &'static str> {
let p = data.as_ptr();
// condition needs to be corrected:
if true {
Ok(p)
}else{
Err("my_error...")
}
}
fn main() {
let data: String = "abc".to_string();
let res = foo(&data);
match res {
Ok(v) => println!("{:?}", v),
Err(e) => println!("{:?}", e),
}
}
How modify the code for returns a result for different data types ,
for example:
for data type i8, u8, ... - "my_error..." (method as_ptr() does not exist)
for data whose types have a pointer - a pointer.
Something like this
fn foo<T>(data: &T) -> Result<*const u8, &'static str> {
// modify code for get pointer or my_error
}
fn main() {
// let data: String = "abc".to_string();
// for this, want to get "my_error":
let data: u8 = 33;
let res = foo(&data);
match res {
Ok(v) => println!("{:?}", v),
Err(e) => println!("{:?}", e),
}
}
You mean you want function overloading? That's not possible in Rust, but you could make a trait and implement it for specific types, then bound your T on that trait.
The simplest way to have different param types and return types for a single function is to use an enum for both the param and the return type. However, normally separate functions would be used for this in Rust -- can you explain why you want to do this with a single function?
Ok. Then using an enum does sound like the right way to experiment with this. You can't use a generic param type like this: foo<T>(data: &T). For a generic param type, the actual/concrete type is chosen by the caller, so foo has no way to know what the actual type is. By using an enum, foo can match on the enum to determine what was passed.
Note that Rust is statically typed and has no general introspection capability for determining the type of a value at runtime.