【发布时间】:2020-12-15 14:39:49
【问题描述】:
我想创建一个函数,它接受x 和y 坐标值并返回格式为(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
}
}
这给了我错误:
|
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
|
添加'static 生命周期似乎会导致此函数出现许多其他问题?我该如何解决这个问题?
【问题讨论】:
-
返回一个字符串。
-
有个有用的
format!宏。
标签: string rust formatting lifetime borrow-checker