繁体   English   中英

返回 Rust 中的格式化字符串

[英]Return a Formatted String in Rust

我想创建一个 function ,它采用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
    }
}

这给了我错误:

   |
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生命周期似乎会导致此 function 出现许多其他问题? 我怎样才能解决这个问题?

更惯用的方法是为您的类型Coord实现Display特征,这将允许您直接对其调用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)"
}

操场

你试图做的事情是不可能的。 您正在创建的String是 function 的本地字符串,您正在尝试返回对它的引用。

j将在 function 的末尾删除,因此您不能返回对它的引用。

您将不得不返回一个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;
}

操场


一个更好的方法来做同样的事情:

fn coords(x: i32, y: i32) -> String {
    let x = format!("({},{})", x, y);
    println!("{}", x);
    return x;
}

操场

这最终为我工作:


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; 
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM