This code returns a pointer, for example 0x625f02281b50
play
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.
1 Like
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?
1 Like
Thanks for your help.
For learning and understanding.
To get this layout for all types of data.
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.
1 Like
I am in favor of enum,
but using the example of two types
of my code (String and u8),
Please, show how to do it correctly.
Here is a modified playground.
But also be sure to read about how to use enum and match in the Rust book.
1 Like
You helped to correct the mistake, thank you very much.
1 Like