返回 Rust 中的格式化字符串

ANi*_*120 1 string formatting lifetime rust borrow-checker

我想创建一个函数,它接受xy坐标值并返回以下格式的字符串(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
    }
}
Run Code Online (Sandbox Code Playgroud)

这给了我错误:

   |
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
   |
Run Code Online (Sandbox Code Playgroud)

添加'static生命周期似乎会导致该函数出现许多其他问题?我怎样才能解决这个问题?

kfe*_*v91 5

更惯用的方法是Display为您的类型实现特征Coord,这将允许您to_string()直接调用它,并且还允许您println!直接在宏中使用它。例子:

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)"
}
Run Code Online (Sandbox Code Playgroud)

操场