pg 138. problem

38 views
Skip to first unread message

Hal Arnold

unread,
Aug 30, 2020, 3:20:33 AM8/30/20
to Begin Rust
msnoyman: I'm at a loss to figure out how to use a method in the implementation of the Fruit<i32> and use it to return a Fruit<String> [if I'm on the right track]. It seems you want something like:

struct Fruit<T> {
    apples: T,
    bananas: T,
}
impl Fruit<i32> {
    fn new() -> Self {
        Fruit {
            apples: 5,
            bananas: 10,
        }
    }
    fn stringy() -> Fruit<String>{
        Fruit {
            apples: "5".to_string(),
            bananas: "10".to_string(),
        }
    }
}
fn main() {
    let fruit_i32: Fruit<i32> = Fruit::new();
    let fruit_str: Fruit<String> = fruit_i32.stringy();
    assert_eq!(fruit_str.apples, "5".to_owned());
    assert_eq!(fruit_str.bananas, "10".to_owned());
    println!("Success!");
}
But of course, this doesn't compile and hence, doesn't work. But this does [I gotta go back and read the 'self as the first implied parameter section'

struct Fruit<T> {
    apples: T,
    bananas: T,
}
impl Fruit<i32> {
    fn new() -> Self {
        Fruit {
            apples: 5,
            bananas: 10,
        }
    }
    fn stringy(self) -> Fruit<String>{
        Fruit {
            apples: "5".to_string(),
            bananas: "10".to_string(),
        }
    }
}
fn main() {
    let fruit_i32: Fruit<i32> = Fruit::new();
    let fruit_str: Fruit<String> = fruit_i32.stringy();
    assert_eq!(fruit_str.apples, "5".to_owned());
    assert_eq!(fruit_str.bananas, "10".to_owned());
    println!("Success!");
}


Michael Snoyman

unread,
Aug 30, 2020, 8:22:38 AM8/30/20
to Hal Arnold, Begin Rust
Hey Hal,

The second answer is actually very close to the solution I would write. There is one mistake, and one improvement. I'll try to hint at both of them, but if you want a direct answer, just ask and I'll say it more directly :)

1. Mistake: You've currently hard-coded 5 and 10 as the fields that come out of stringy. Instead, you should use the values in the original self value, via self.apples and self.bananas.
2. Improvement: What if I want to use fruit_i32 after I call the stringy method? Right now, it will be a use-after-move error. Is there a _different_ way of making the method besides a plain old `self`?

HTH, if you have further questions let us know!

Michael

--
You received this message because you are subscribed to the Google Groups "Begin Rust" group.
To unsubscribe from this group and stop receiving emails from it, send an email to begin-rust+...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/begin-rust/1d311c01-4261-499b-a126-707de32d84d2n%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Hal Arnold

unread,
Aug 30, 2020, 1:21:25 PM8/30/20
to Michael Snoyman, Begin Rust
Thanks! Let me chew alittle
Reply all
Reply to author
Forward
0 new messages