Macro anony::struct

source ·
struct!() { /* proc-macro */ }
Expand description

Creates an instance of an anonymous struct.

Note: if two instances are created from two different r#struct!s, they will guarantee belong to two differences anonymous structs even if they have exactly the same set of fields (both names and types). You can clone an instance instead to get the same fields and type for the cloned instance.

§Examples

Like how an instance of a normal struct is constructed, you can do the same with this macro:

use anony::r#struct;

let address = "123 St. SW";

let o1 = r#struct! {
    name: "Alice",
    age: 28,
    address,
};

assert_eq!(o1.name, "Alice");
assert_eq!(o1.age, 28);
assert_eq!(o1.address, "123 St. SW");

// other anonymous constructs are allowed too!
let _o2 = r#struct! {
    closure: || 3,
    future: async {
        let x = "Hello, world!".to_owned();
        std::future::ready(()).await;
        x.len()
    },
    anonymous: r#struct! {
        f1: 3.4,
        f2: Box::new("123"),
    },
};

You can move fields one by one:

use anony::r#struct;

let address = "123 St. SW".to_owned();

let o1 = r#struct! {
    name: "Alice".to_owned(),
    age: 28,
    address,
};

let name = o1.name;
let age = o1.age;
let address = o1.address;

assert_eq!(name, "Alice");
assert_eq!(age, 28);
assert_eq!(address, "123 St. SW");

Pinning projection (use project_ref for Pin<&_> and project_mut for Pin<&mut _>, like you use pin-project crate). The struct created by project_ref (not project_mut) implements Clone and Copy:

use std::pin::pin;
use std::future::Future;
use std::task::Context;
use std::task::Poll;
use anony::r#struct;
use futures::task::noop_waker;

let o1 = r#struct! {
    fut: async {
        let s = "10011001001";
        s.matches("1").count()
    }
};

let o1 = pin!(o1);
let waker = noop_waker();
let mut cx = Context::from_waker(&waker);

// Project to the `fut` field
assert_eq!(o1.project_mut().fut.poll(&mut cx), Poll::Ready(5));

§Implemented traits

This struct implements the following if all of its fields are implemented them: