Crate petname

source ·
Expand description

You can populate Petnames with your own word lists, but the word lists from upstream petname are included with the default-words feature (enabled by default). See Petnames::small, Petnames::medium, and Petnames::large to select a particular built-in word list, or use Petnames::default.

The other thing you need is a random number generator from rand:

use petname::Generator; // Trait needs to be in scope for `generate`.
let mut rng = rand::thread_rng();
let name = petname::Petnames::default().generate(&mut rng, 7, ":").expect("no names");

It may be more convenient to use the default random number generator:

use petname::Generator; // Trait needs to be in scope for `generate_one`.
let name = petname::Petnames::default().generate_one(7, ":").expect("no names");

There’s a convenience function that’ll do all of this:

let name = petname::petname(7, ":");

But the most flexible approach is to create an Iterator with iter:

use petname::Generator; // Trait needs to be in scope for `iter`.
let mut rng = rand::thread_rng();
let petnames = petname::Petnames::default();
let ten_thousand_names: Vec<String> =
  petnames.iter(&mut rng, 3, "_").take(10000).collect();

You can modify the word lists to, for example, only use words beginning with the letter “b”:

let mut petnames = petname::Petnames::default();
petnames.retain(|s| s.starts_with("b"));
let name = petnames.generate_one(3, ".").expect("no names");
assert!(name.starts_with('b'));

There’s another way to generate alliterative petnames which is useful when you you don’t need or want each name to be limited to using the same initial letter as the previous generated name. Create the Petnames as before, and then convert it into an Alliterations:

let mut petnames = petname::Petnames::default();
let mut alliterations: petname::Alliterations = petnames.into();
alliterations.generate_one(3, "/").expect("no names");

Both Petnames and Alliterations implement Generator; this needs to be in scope in order to generate names. It’s object-safe so you can use Petnames and Alliterations as trait objects:

use petname::Generator;
let generator: &dyn Generator = &petname::Petnames::default();
let generator: &dyn Generator = &petname::Alliterations::default();

Structs§

  • Word lists prepared for alliteration.
  • Word lists and the logic to combine them into petnames.

Traits§

  • Trait that defines a generator of petnames.

Functions§

  • Convenience function to generate a new petname from default word lists.

Type Aliases§