From caffa9b7ab70220ccb3792bad69ee039ffbe12dc Mon Sep 17 00:00:00 2001 From: George Bateman Date: Sun, 23 Oct 2022 00:04:31 +0100 Subject: [PATCH 1/2] Document visibility annotation --- book/src/SUMMARY.md | 1 + book/src/visibility.md | 31 +++++++++++++++++++++++++++++++ 2 files changed, 32 insertions(+) create mode 100644 book/src/visibility.md diff --git a/book/src/SUMMARY.md b/book/src/SUMMARY.md index f9cc869f12..e7feff9523 100644 --- a/book/src/SUMMARY.md +++ b/book/src/SUMMARY.md @@ -20,6 +20,7 @@ - [Preventing the Derivation of `Debug`](./nodebug.md) - [Preventing the Derivation of `Default`](./nodefault.md) - [Annotating types with `#[must-use]`](./must-use-types.md) + - [Field visibility](./visibility.md) - [Generating Bindings to C++](./cpp.md) - [Generating Bindings to Objective-c](./objc.md) - [Using Unions](./using-unions.md) diff --git a/book/src/visibility.md b/book/src/visibility.md new file mode 100644 index 0000000000..039018fcdf --- /dev/null +++ b/book/src/visibility.md @@ -0,0 +1,31 @@ +# Making fields private + +Fields can be made private for various reasons. You may wish to enforce some invariant on the fields of a structure, which cannot be achieved if the field is public and can be set by any code. For example, you may wish to ensure that a pointer always points to something appropriate. + +### Annotation + +```c +struct OneFieldPrivate { + /** Null-terminated, static string.
*/ + const char *s; + bool b; +}; + +/**
*/ +struct MostFieldsPrivate { + int a; + bool b; + /**
*/ + char c; +}; +``` + +Then in Rust: + +```rust +impl OneFieldPrivate { + pub fn new(s: &'static core::ffi::CStr, b: bool) -> Self { + OneFieldPrivate { s: s.as_ptr(), b } + } +} +``` From fc56c70500d8a6845ab2a7b886425905818a56b5 Mon Sep 17 00:00:00 2001 From: George Bateman Date: Sun, 23 Oct 2022 00:13:47 +0100 Subject: [PATCH 2/2] Make doctests pass --- book/src/visibility.md | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/book/src/visibility.md b/book/src/visibility.md index 039018fcdf..ac0aac15da 100644 --- a/book/src/visibility.md +++ b/book/src/visibility.md @@ -23,8 +23,14 @@ struct MostFieldsPrivate { Then in Rust: ```rust +# #[repr(C)] +# pub struct OneFieldPrivate { +# s: *const ::std::os::raw::c_char, +# pub b: bool, +# } + impl OneFieldPrivate { - pub fn new(s: &'static core::ffi::CStr, b: bool) -> Self { + pub fn new(s: &'static std::ffi::CStr, b: bool) -> Self { OneFieldPrivate { s: s.as_ptr(), b } } }