Owning struct from another struct in new()

Hello,

I would appreciate if you could give me some hint on owning a struct from another struct. Sample code(struct definitions are skippe).

How to let 'Bar' owns 'Foo' instead of borrowing 'Foo'.

impl Foo
{
  pub fn new() -> Self()
  {
     Foo
     {
       name: "",
       age: 20
     }
  }
}


impl struct Bar
{
   pub fn new() -> Self
   {
      Bar
      {
        // How to make 'bar' owns the foo instance instead of borrowing? (borrowing is not correct here obviously)
        // clone and copy do not work. e.g, foo::new().clone(), foo::new().copy() 
        bar: foo::new(),       
        cookie: "cookie"
      }
    }
}

Another question is it possible to make a const variable using non-constant function?

pub const BIGINT_ZERO: Integer = rug::Integer::from(0);
`error[E0015]: cannot call non-const fn `<Integer as From<i32>>::from` in constants`

Thanks a lot.

Why do you think that bar has only a reference to foo?

Foo::new() returns a value of Foo. So Bar becomes the owner of the returned value, doesn't it?

I think your code doesn't work as you've posted it:

impl Foo
{
  pub fn new() -> Self() // remove ()
  ...
}


impl struct Bar
{
   pub fn new() -> Self
   ...
        bar: foo::new(), // foo should be Foo
   ...
}

2 Likes

This compiles. Perhaps modify it to better explain the problem you're encountering.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.