-3

I am try to convert a int to binary with 000 in the front, my code is

fn int32_to_binerystr(i: &i32, width: &usize) -> str {
   let mut s = format!("{:032b}", i);
   let from = s.len() - width;
   let to = s.len();
   s[from..to]
}

it complian about :

   the size for values of type `str` cannot be known at compilation time
   the trait `Sized` is not implemented for `str`
   the return type of a function must have a statically known size rustcE0277

how to fix this?

En Xie
  • 510
  • 4
  • 19

2 Answers2

1

You cannot return a str (because it is not sized), nor a &str (if it is not static). You just need to take ownership of it with str::to_owned or str::to_string:

fn int32_to_binerystr(i: &i32, width: &usize) -> String {
   let s = format!("{:032b}", i);
   let from = s.len() - width;
   let to = s.len();
   s[from..to].to_string()
}

Playground

Netwave
  • 40,134
  • 6
  • 50
  • 93
0

'str' is not sized, since it represents a string of unknown length.

You probably want a String or a &str instead

cameron1024
  • 9,083
  • 2
  • 16
  • 36