0

The following snippet doesn't compile

fn main() {
    let my_string = String::from("Meow");
    
    let _x = Box::new(*my_string); 
}

The error message is:

error[E0277]: the size for values of type `str` cannot be known at compilation time
   --> src/main.rs:4:23
    |
4   |     let _x = Box::new(*my_string); 
    |                       ^^^^^^^^^^ doesn't have a size known at compile-time
    |
    = help: the trait `Sized` is not implemented for `str`
note: required by `Box::<T>::new`

error[E0277]: the size for values of type `str` cannot be known at compilation time
 --> src/main.rs:4:14
  |
4 |     let _x = Box::new(*my_string); 
  |              ^^^^^^^^ doesn't have a size known at compile-time
  |
  = help: the trait `Sized` is not implemented for `str`
  = note: all function arguments must have a statically known size

For more information about this error, try `rustc --explain E0277`.

Since Box is Box<T: ?Sized>, i don't understand the helper message help: the trait `Sized` is not implemented for `str` , and why Box::new(*my_string) fails.

To obtain a Box, i need to call into_boxed_str()

The following snippet compiles:

fn main() {
    let my_string = String::from("Meow");
    
    let _x = my_string.into_boxed_str(); 
}
Jerboas86
  • 596
  • 4
  • 12
  • I think you've been mislead by your own example here. `let _x = *my_string;` also doesn't compile with a similar error, and it's unclear why you'd think it should compile. Unsized values can only exist through references, or (smart) pointers, such as `Box`. Binding `*my_string` of type `str`, either to a variable, or to a function parameter (`Box::new` is just a regular function), is not possible. – mcarton Nov 15 '21 at 10:03
  • 1
    Same issue, except that we have the unsized primitive type `str` instead of a trait object. Since it is unsized, it cannot be passed to `Box::new`. – E_net4 Nov 15 '21 at 10:08
  • @E_net4thevoter Yes, it does answer my question. thanks – Jerboas86 Nov 15 '21 at 10:11

0 Answers0