I'd like to create a function that takes an x
and y
coordinate values and returns a string of the format (x,y)
:
pub struct Coord {
x: i32,
y: i32,
}
fn main() {
let my_coord = Coord {
x: 10,
y: 12
};
let my_string = coords(my_coord.x, my_coord.y);
fn coords(x: i32, y: i32) -> &str{
let l = vec!["(", x.to_string(), ",", y.to_string(), ")"];
let j = l.join("");
println!("{}", j);
return &j
}
}
This gives me the error:
|
14 | fn coords(x: i32, y: i32) -> &str {
| ^ expected named lifetime parameter
|
= help: this function's return type contains a borrowed value with an elided lifetime, but the lifetime cannot be derived from the arguments
help: consider using the `'static` lifetime
|
Adding the 'static
lifetime seems to cause a host of other problems with this function? How can I fix this?
The more idiomatic approach would be to implement the Display
trait for your type Coord
which would allow you to call to_string()
on it directly, and also would allow you to use it in the println!
macro directly. Example:
use std::fmt::{Display, Formatter, Result};
pub struct Coord {
x: i32,
y: i32,
}
impl Display for Coord {
fn fmt(&self, f: &mut Formatter) -> Result {
write!(f, "({}, {})", self.x, self.y)
}
}
fn main() {
let my_coord = Coord { x: 10, y: 12 };
// create string by calling to_string()
let my_string = my_coord.to_string();
println!("{}", my_string); // prints "(10, 12)"
// can now also directly pass to println! macro
println!("{}", my_coord); // prints "(10, 12)"
}
What you are trying to do is not possible. The String
you are creating is local to the function and you are trying to return a reference to it.
j
will be dropped at the end of the function, so you can't return a reference to it.
You will have to return a String
:
fn coords(x: i32, y: i32) -> String {
let l = vec![
"(".into(),
x.to_string(),
",".into(),
y.to_string(),
")".into(),
];
let j = l.join("");
println!("{}", j);
return j;
}
A better way to do the same:
fn coords(x: i32, y: i32) -> String {
let x = format!("({},{})", x, y);
println!("{}", x);
return x;
}
this ended up working for me:
pub struct Coord{
x: i32,
y: i32,
}
fn main(){
let my_coord = Coord{
x: 10,
y: 12
};
let my_string = coords(my_coord.x, my_coord.y);
fn coords(x: i32, y: i32) -> String{
let myx = x.to_string();
let myy = y.to_string();
let l = vec!["(", &myx, ",", &myy, ")"];
let j = l.join("");
return j;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.