Discussion
Loading...

Post

Log in
  • About
  • Code of conduct
  • Privacy
  • Users
  • Instances
  • About Bonfire
Marc
@corpsmoderne@mamot.fr  ·  activity timestamp 4 hours ago

Ok I'm tired... In #ratatui How Am I supposed to return a Span<'> from a function ? Where does this lifetime comes from? #rustlang

everything is owned in my function:

fn display_battery_level(bat: f32) -> Span<'> {
let bat_s = bat.to_string();
match bat {
_ if bat > 50.0 => bat_s.green(),
_ if bat > 25.0 => bat_s.yellow(),
_ => bat_s.red(),
}
}

  • Copy link
  • Flag this post
  • Block
Damian Poddebniak
@duesee@norden.social  ·  activity timestamp 3 hours ago
@corpsmoderne You could try to return a `Span<'static>` like https://play.rust-lang.org/?version=stable&mode=debug&edition=2024. Maybe the last line in https://docs.rs/ratatui/latest/ratatui/text/struct.Span.html#method.styled works?
  • Copy link
  • Flag this comment
  • Block
Kornel
@kornel@mastodon.social  ·  activity timestamp 4 hours ago
@corpsmoderne You can't. It borrows from a value created inside the function. You can only return temporary references to values that existed before the function has been called.
  • Copy link
  • Flag this comment
  • Block
Marc
@corpsmoderne@mamot.fr  ·  activity timestamp 4 hours ago
@kornel sorry it wasn't clear in my post I know why this is not working, my question is that I don't understand how I'm supposed to use this specific data structure of #ratatui
  • Copy link
  • Flag this comment
  • Block
Marc
@corpsmoderne@mamot.fr  ·  activity timestamp 4 hours ago
@kornel ha, sorry that was the "I'm tired" part of the post. I didn't realize it borrowed from bat_s. So this should work:

fn display_battery_level<'a>(bat: f32, bat_s: &'a str) -> Span<'a> {
match bat {
_ if bat > 50.0 => bat_s.green(),
_ if bat > 25.0 => bat_s.yellow(),
_ => bat_s.red(),
}
}

  • Copy link
  • Flag this comment
  • Block
Log in

bonfire.cafe

A space for Bonfire maintainers and contributors to communicate

bonfire.cafe: About · Code of conduct · Privacy · Users · Instances
Bonfire social · 1.0.0-rc.2.3 no JS en
Automatic federation enabled
  • Explore
  • About
  • Members
  • Code of Conduct