Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Trying to return a union - Help needed #46

Open
asafyish opened this issue Feb 13, 2018 · 1 comment
Open

Trying to return a union - Help needed #46

asafyish opened this issue Feb 13, 2018 · 1 comment

Comments

@asafyish
Copy link

Hi,

I have this schema:

struct Square {
  width @0 :Int64;
  height @1 :Text;
}

struct Circle {
  radius @0 :Int64;
}

struct Shape {
   union {
    square @0 :Square;
    circle @1 :Circle;
  }
}

I am trying to write a function that returns a mutable square or circle but don't want the caller to know about shape (not even sure it's possible in rust, because of ownership).

I tried:

pub fn get_square() -> ?? {
    let mut message = capnp::message::Builder::new_default();
    let mut message2 = capnp::message::Builder::new_default();
    let mut shape = message2.init_root::<Shape::Builder>();
    {
        let square = message.init_root::<Square::Builder>();
        shape.set_square(square.borrow_as_reader());
    }
   // How to return square ?? Is it possible ?
}

What I am trying to achieve is, having a module that expose several functions that let me create a square or circle, but without knowing about the internal parts of capnp.

@dwrensha
Copy link
Member

I'm not sure I understand the question. Does something like the following solve your problem?

enum SquareOrCircle<'a> {
   Square(Square::Builder<'a>),
   Circle(Circle::Builder<'a>),
}

fn get_square<'a>(messge: &'a mut capnp::message::Builder) -> capnp::Result<SquareOrCircle<'a>> {
   let mut root: Shape::Builder = message.get_root()?;
   match root.which()? {
     Shape::Square(square) => SquareOrCircle::Square(square?),
     Shape::Circle(circl) => SquareOrCircle::Circle(circle?),
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants