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

Don’t recommend empty enums for opaque types #44

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 7 additions & 5 deletions src/ffi.md
Original file line number Diff line number Diff line change
Expand Up @@ -737,11 +737,11 @@ void foo(struct Foo *arg);
void bar(struct Bar *arg);
```

To do this in Rust, let’s create our own opaque types with `enum`:
To do this in Rust, let’s create our own opaque types:

```rust
pub enum Foo {}
pub enum Bar {}
#[repr(C)] pub struct Foo { _private: [u8; 0] }
#[repr(C)] pub struct Bar { _private: [u8; 0] }

extern "C" {
pub fn foo(arg: *mut Foo);
Expand All @@ -750,7 +750,9 @@ extern "C" {
# fn main() {}
```

By using an `enum` with no variants, we create an opaque type that we can’t
instantiate, as it has no variants. But because our `Foo` and `Bar` types are
By including a private field and no constructor,
we create an opaque type that we can’t instantiate outside of this module.
An empty array is both zero-size and compatible with `#[repr(C)]`.
But because our `Foo` and `Bar` types are
different, we’ll get type safety between the two of them, so we cannot
accidentally pass a pointer to `Foo` to `bar()`.