3

I am having problems in an exercise where I try to get an impl block to return the value of the i32 in the struct in str format. I don't know if it is doing well or if it is possible to do this, this is the complete error:

error[E0277]: the size for values of type `str` cannot be known at compilation time
 --> src/main.rs:6:20
  |
6 |     fn x(&self) -> str {
  |                    ^^^ doesn't have a size known at compile-time
  |
  = help: the trait `std::marker::Sized` is not implemented for `str`
  = note: to learn more, visit <https://doc.rust-lang.org/book/ch19-04-advanced-types.html#dynamically-sized-types-and-the-sized-trait>
  = note: the return type of a function must have a statically known size

error[E0308]: mismatched types
 --> src/main.rs:9:9
  |
6 |     fn x(&self) -> str {
  |                    --- expected `str` because of return type
...
9 |         *_newword
  |         ^^^^^^^^^ expected `str`, found struct `std::string::String`

error[E0277]: the size for values of type `str` cannot be known at compilation time
   --> src/main.rs:17:5
    |
17  |     println!("x is: {}", f.x());
    |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time
    |
    = help: the trait `std::marker::Sized` is not implemented for `str`
    = note: to learn more, visit <https://doc.rust-lang.org/book/ch19-04-advanced-types.html#dynamically-sized-types-and-the-sized-trait>
    = note: this error originates in a macro outside of the current crate (in Nightly builds, run with -Z external-macro-backtrace for more info)

This is the code that I am trying to make work:

struct Foo<'a> {
    x: &'a i32,
}

impl<'a> Foo<'a> {
    fn x(&self) -> str {
        let word = *self.x;
        let _newword = &word.to_string();
        *_newword
    }
}

fn main() {
    let y = &5;
    let f = Foo { x: y };

    println!("x is: {}", f.x());
}
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366

0 Answers0