Skip to main content

MessageField

Struct MessageField 

Source
pub struct MessageField<T>
where T: Default,
{ /* private fields */ }
Expand description

A wrapper for optional message fields that provides transparent access to a default instance when the field is not set.

This type is used for singular message fields in generated code. It avoids the ergonomic pain of Option<Box<M>> while still being heap-allocated only when set (no allocation for unset fields).

§Access patterns

// Reading through an unset field gives the default:
let msg = Outer::default();
assert_eq!(msg.inner.name, "");  // No unwrap needed, derefs to default

// Check if set:
if msg.inner.is_set() { ... }

// Set a value:
msg.inner = MessageField::some(Inner { name: "hello".into(), ..Default::default() });

// Clear:
msg.inner = MessageField::none();

Implementations§

Source§

impl<T> MessageField<T>
where T: Default,

Source

pub const fn none() -> MessageField<T>

Create a MessageField with no value set.

Source

pub fn some(value: T) -> MessageField<T>

Create a MessageField with a value.

Source

pub fn from_box(value: Box<T>) -> MessageField<T>

Create a MessageField from a boxed value.

Source

pub fn is_set(&self) -> bool

Returns true if the field has a value set.

Source

pub fn is_unset(&self) -> bool

Returns true if the field has no value set.

Source

pub fn as_option(&self) -> Option<&T>

Get a reference to the inner value, or None if unset.

Source

pub fn as_option_mut(&mut self) -> Option<&mut T>

Get a mutable reference to the inner value, or None if unset.

Source

pub fn take(&mut self) -> Option<T>

Take the inner value, leaving the field unset.

Source

pub fn get_or_insert_default(&mut self) -> &mut T

Get a mutable reference to the value, initializing to the default if unset.

Source

pub fn modify<F>(&mut self, f: F)
where F: FnOnce(&mut T),

Call f with a mutable reference to the inner value, initializing to the default if the field is currently unset.

This is the ergonomic write counterpart to the transparent read provided by Deref. Instead of calling get_or_insert_default once per assignment:

msg.address.get_or_insert_default().street = "123 Main St".into();
msg.address.get_or_insert_default().city   = "Springfield".into();

use modify to initialize the field once and set all sub-fields in the closure:

msg.address.modify(|a| {
    a.street = "123 Main St".into();
    a.city   = "Springfield".into();
});
Source

pub fn into_option(self) -> Option<T>

Consume the field, returning Some(T) if set or None if unset.

This unboxes the inner value. For in-place extraction that leaves the field unset without consuming the enclosing struct, see take.

Source

pub fn ok_or<E>(self, err: E) -> Result<T, E>

Consume the field, returning Ok(T) if set or Err(err) if unset.

Mirrors Option::ok_or. Useful for enforcing presence of semantically-required fields that the proto schema leaves optional:

let cmd = request.normalized_command.ok_or(Error::MissingCommand)?;
Source

pub fn ok_or_else<E, F>(self, err: F) -> Result<T, E>
where F: FnOnce() -> E,

Consume the field, returning Ok(T) if set or Err(err()) if unset.

Mirrors Option::ok_or_else. The closure is only called if the field is unset, so use this over ok_or when constructing the error is non-trivial:

let cmd = request.normalized_command.ok_or_else(|| {
    ConnectError::invalid_argument("missing normalized_command in request")
})?;

Trait Implementations§

Source§

impl<T> Clone for MessageField<T>
where T: Default + Clone,

Source§

fn clone(&self) -> MessageField<T>

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<T> Debug for MessageField<T>
where T: Default + Debug,

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl<T> Default for MessageField<T>
where T: Default,

Source§

fn default() -> MessageField<T>

Returns the “default value” for a type. Read more
Source§

impl<T> Deref for MessageField<T>
where T: DefaultInstance,

Source§

type Target = T

The resulting type after dereferencing.
Source§

fn deref(&self) -> &T

Dereferences the value.
Source§

impl<T> From<Option<T>> for MessageField<T>
where T: Default,

Source§

fn from(opt: Option<T>) -> MessageField<T>

Converts to this type from the input type.
Source§

impl<T> From<T> for MessageField<T>
where T: Default,

Source§

fn from(value: T) -> MessageField<T>

Converts to this type from the input type.
Source§

impl<T> PartialEq for MessageField<T>

Source§

fn eq(&self, other: &MessageField<T>) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<T> Eq for MessageField<T>

Auto Trait Implementations§

§

impl<T> Freeze for MessageField<T>

§

impl<T> RefUnwindSafe for MessageField<T>
where T: RefUnwindSafe,

§

impl<T> Send for MessageField<T>
where T: Send,

§

impl<T> Sync for MessageField<T>
where T: Sync,

§

impl<T> Unpin for MessageField<T>

§

impl<T> UnsafeUnpin for MessageField<T>

§

impl<T> UnwindSafe for MessageField<T>
where T: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<P, T> Receiver for P
where P: Deref<Target = T> + ?Sized, T: ?Sized,

Source§

type Target = T

🔬This is a nightly-only experimental API. (arbitrary_self_types)
The target type on which the method may be called.
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.