Skip to content

flier/named-tuple.rs

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

18 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

named-tuple.rs

A macro for declaring a struct that manages a set of fields in a tuple.

Travis-CI Status Latest version Documentation License

Getting Started

named-tuple.rs is available on crates.io. It is recommended to look there for the newest released version, as well as links to the newest builds of the docs.

At the point of the last update of this README, the latest published version could be used like this:

Add the following dependency to your Cargo manifest...

[dependencies]
named_tuple = "0.1"

...and see the docs for how to use it.

Example

#[macro_use]
extern crate named_tuple;

named_tuple!(
    #[derive(Clone, Copy, Debug, Default, Hash, PartialEq)]
    struct Human<'a> {
        name: &'a str,
        age: usize,
    }
);

named_tuple!(
    #[derive(Copy, Debug)]
    struct Endpoint(host, port);
);

fn main() {
    /// structs with named fields
    let mut human = Human::new("alice", 18);

    assert_eq!(Human::field_names(), &["name", "age"]);
    assert_eq!(human.fields(), (("name", "alice"), ("age", 18)));
    assert_eq!(human.field_values(), ("alice", 18));

    assert_eq!(human.name(), "alice");
    assert_eq!(human.age(), 18);

    assert_eq!((human.0).0, "alice");
    assert_eq!((human.0).1, 18);

    assert_eq!(format!("{:?}", human), "Human { name: \"alice\", age: 18 }");

    human.set_name("bob");
    assert_eq!(human, ("bob", 18));

    human.set_age(20);
    assert_eq!(human, Human::from(("bob", 20)));

    let t: (&str, usize) = human.into();

    assert_eq!(t, ("bob", 20));

    // tuple structs
    let mut endpoint = Endpoint::new("localhost", 80);

    assert_eq!(endpoint.field_names(), &["host", "port"]);
    assert_eq!(endpoint.fields(), (("host", "localhost"), ("port", 80)));
    assert_eq!(endpoint.field_values(), ("localhost", 80));

    assert_eq!(endpoint.host(), "localhost");
    assert_eq!(endpoint.port(), 80);

    assert_eq!(
        format!("{:?}", endpoint),
        "Endpoint { host: \"localhost\", port: 80 }"
    );

    endpoint.set_host("google.com");
    endpoint.set_port(443);

    assert_eq!(("google.com", 443), endpoint.into());
}

License

Licensed under either of

at your option.

Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

About

A macro for declaring a struct that manages a set of fields in a tuple.

Resources

License

Apache-2.0, MIT licenses found

Licenses found

Apache-2.0
LICENSE-APACHE
MIT
LICENSE-MIT

Stars

Watchers

Forks

Packages

No packages published

Languages