Skip to content

Commit 3575c9f

Browse files
Merge pull request #1021 from SimonSapin/patch-1
Don’t recommend empty enums for opaque types
2 parents ec65990 + a3d7bc2 commit 3575c9f

File tree

1 file changed

+7
-5
lines changed

1 file changed

+7
-5
lines changed

first-edition/src/ffi.md

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -737,11 +737,11 @@ void foo(struct Foo *arg);
737737
void bar(struct Bar *arg);
738738
```
739739
740-
To do this in Rust, let’s create our own opaque types with `enum`:
740+
To do this in Rust, let’s create our own opaque types:
741741
742742
```rust
743-
pub enum Foo {}
744-
pub enum Bar {}
743+
#[repr(C)] pub struct Foo { private: [u8; 0] }
744+
#[repr(C)] pub struct Bar { private: [u8; 0] }
745745
746746
extern "C" {
747747
pub fn foo(arg: *mut Foo);
@@ -750,7 +750,9 @@ extern "C" {
750750
# fn main() {}
751751
```
752752

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

0 commit comments

Comments
 (0)