Skip to content

Rust

The Rust generator turns a LinkML schema into a Rust crate, with a struct for each class and an enum for each enum. serde loads and dumps the data, and PyO3 makes the structs Python classes, each behind a Cargo feature.

This generator started as a port of the Rust generator of LinkML-Python, written by Jonny Saunders and Frank Dekervel. It generates the same kinds of structs, enums and traits. There are small differences in some names of classes, enums and enum variants, and with the Rust types of integers and datetimes. The ohi LinkML generator also includes many bug fixes and improvements. See Differences from LinkML-Python.

  • The crate doesn’t need a LinkML runtime.
  • It depends on chrono for dates and times. With --date-type string, they are strings, and chrono isn’t needed.
  • The code that loads and dumps the data with serde is generated by default. The PyO3 code is generated with --python pyo3, and --python pyo3_stubs also adds the code for Python type stubs. In a crate, this code is behind the Cargo features serde, pyo3 and stubgen, which are on by default and bring their dependencies. A single .rs file has no features, see One file.
Terminal window
ohi get w3c/prov-o
ohi linkml to rust --crate-name prov prov-o.linkml.yaml
Try it in the playground, with PROV-O

With --to a directory, the generator writes a crate:

File Content
Cargo.toml The package, its features, and the dependencies that the code uses. The generator writes it only if it doesn’t exist yet, so you can edit it.
pyproject.toml With Python bindings, the build of the Python module with maturin. The generator writes it only if it doesn’t exist yet.
src/lib.rs The type aliases, enums and structs.
src/poly.rs A trait for each class, see Traits.
src/poly_containers.rs The views of lists and maps that the traits return.
src/serde_utils.rs With serde, helpers for the different forms that LinkML data can take.
src/stub_utils.rs, src/bin/stub_gen.rs With --python pyo3_stubs, the program that writes the Python type stubs.

If the schema changes and the new code needs other dependencies, add them to Cargo.toml yourself, or delete it so that the generator writes a new one.

With --to a .rs file, or no --to, it writes the crate as one file, without the traits.

A single .rs file goes into a crate of your own, with your own Cargo.toml. It has no Cargo features. It includes the serde code unless you pass --serde=false, and the PyO3 code only with --python. With the default options, your crate needs serde with its derive feature, serde_json, and chrono (except with --date-type string). The file compiles without warnings.

mod model; // the generated model.rs
pub use model::{Zoo, Animal, Keeper};
crate_namestring
CLI --crate-nameScala crateName

The name of the crate and of its Python module. It must be a Rust identifier. If unset, the schema's name is used, with every character that can't be in an identifier replaced by _.

date_typeRustDateTypedefault chrono
CLI --date-typeScala dateType

The Rust types for date and datetime values.

  • chrono chrono::NaiveDate and chrono::DateTime<FixedOffset>. A datetime must have an offset, as in RFC 3339 and JSON Schema.
  • string String, with the text from the data, unchanged and unchecked. The crate doesn't depend on chrono.
expand_subproperty_ofbooleandefault true
CLI --expand-subproperty-ofScala expandSubpropertyOf

Whether the type of a slot with subproperty_of: X is an enum with a variant for X and for each descendant of X. Otherwise, its type is the Rust type of its range.

handwritten_libbooleandefault false
CLI --handwritten-libScala handwrittenLib

Whether to put the generated code in src/generated/, and leave src/lib.rs for code of your own. src/lib.rs is only written when it doesn't exist yet.

metadata_languagestringdefault en
CLI --metadata-languageScala metadataLanguage

The language of the titles and descriptions in the output, for schemas with text in more than one language.

pythonRustPythondefault none
CLI --python

Which Python bindings to generate. PyO3 needs the serde code, so pyo3 and pyo3_stubs also generate it.

  • none No Python bindings.
  • pyo3 Python classes for the structs, made with PyO3. The crate is a Python extension module, with a #[pymodule] function and a pyproject.toml that builds it with maturin. In a crate, this code is behind the pyo3 feature, which is on by default.
  • pyo3_stubs The same as pyo3, plus the code for the Python type stubs (.pyi files) of the module, made with pyo3-stub-gen. In a crate, this code is behind the stubgen feature, and comes with a stub_gen program that writes the stubs.
serdebooleandefault true
CLI --serde

Whether to generate the code that loads and dumps the data with serde. In a crate, it is behind the serde feature, which is on by default.

With the serde feature, any serde format works, such as YAML:

let zoo: Zoo = yaml_serde::from_str(&text)?; // load
let text = yaml_serde::to_string(&zoo)?; // dump

Loading accepts each form that LinkML allows: a single value for a multivalued slot, and an inlined class as a list or as a dict, with or without the key in each object. Dumping always writes the same form.

This schema:

classes:
Zoo:
tree_root: true
attributes:
name:
required: true
animals:
range: Animal
multivalued: true
inlined_as_list: true
keepers:
range: Keeper
multivalued: true
inlined: true
Animal:
abstract: true
attributes:
kind:
designates_type: true
required: true
name:
required: true
keeper:
range: Keeper
Lion:
is_a: Animal
attributes:
mane_length:
range: float
Parrot:
is_a: Animal
attributes:
words:
multivalued: true
Keeper:
description: A person who looks after animals.
attributes:
id:
identifier: true
name:
since:
range: date
shift:
range: Shift
enums:
Shift:
permissible_values:
day:
night:

generates these structs and enums (we omit here their attributes and the code for serde and PyO3):

pub struct Zoo {
pub animals: Option<Vec<AnimalOrSubtype>>,
pub keepers: Option<HashMap<String, Keeper>>,
pub name: String,
}
pub struct Animal {
pub keeper: Option<String>,
pub kind: String,
pub name: String,
}
pub enum AnimalOrSubtype {
Lion(Lion),
Parrot(Parrot),
}
pub struct Lion {
pub keeper: Option<String>,
pub kind: String,
pub mane_length: Option<f64>,
pub name: String,
}
pub struct Parrot {
pub keeper: Option<String>,
pub kind: String,
pub name: String,
pub words: Option<Vec<String>>,
}
pub struct Keeper {
pub id: String,
pub name: Option<String>,
pub shift: Option<Shift>,
pub since: Option<NaiveDate>,
}
pub enum Shift {
Day,
Night,
}

AnimalOrSubtype picks its variant by the kind of the data, so loading {"name": "Z", "animals": [{"kind": "Lion", "name": "Leo"}]} gives a Zoo whose first animal is a Lion.

Every class becomes a struct with a field for each of its slots, including the ones it inherits through is_a and mixins, ordered by rank and then by name. The titles and descriptions of the class and its slots become doc comments. Every slot also gets a type alias in the module slots, such as slots::mane_length, unless another item of the crate has the same name.

A class with subclasses also gets an OrSubtype enum, with a variant for each subclass, and for the class itself if it isn’t abstract or a mixin. A field whose range is the class has this enum as its type. serde picks the variant by the type designator of the class, if it has one, and otherwise tries the variants in turn, and the first variant that can read the data wins. The subclasses come in the order of their rank and then their name, so rank decides between two subclasses that can read the same data. The class itself comes last.

A class with the linkml:Any URI and no slots becomes a struct that wraps a serde_json::Value, so it reads any YAML or JSON value. If a schema has more than one such class, one of them gets the struct (Anything if the schema has it), and the others become type aliases of it.

With the annotation rust.linkml.io/generate/merge: true, a struct derives Merge and gets a merge_with method, which keeps the values that the other struct doesn’t have.

src/poly.rs has a trait for each class, with a getter for each slot that the class adds to its parents. The trait extends the traits of its is_a parent and its mixins, and the structs and OrSubtype enums of the class and its descendants implement it. So the same code can read a slot from the class and from any of its subclasses:

use zoo::poly::Animal;
fn names(zoo: &zoo::Zoo) -> Vec<&str> {
zoo.animals.iter().flatten().map(|a| Animal::name(a)).collect()
}

A getter returns a Vec or a HashMap as a borrowed view, a Copy value by value, and other values by reference. If the slot has different ranges in the descendants, the getter returns a union of them.

LinkML range Rust
string, uri, curie, uriorcurie, ncname, time and types based on them String, through an alias such as uriorcurie
integer i64
float, double, decimal f64
boolean bool
date chrono::NaiveDate, or String with --date-type string
datetime chrono::DateTime<FixedOffset>, which needs an offset, as in RFC 3339 and JSON Schema. With --date-type string, a String, which also accepts values without an offset
langstring LocalizedText, a String or a BTreeMap<String, String> from language tag to text
an enum the enum, or String if the enum has no permissible values
a class, not inlined the identifier, of the Rust type of the identifier’s range, such as String or i64
a class, inlined the struct, or its OrSubtype enum. A value that can contain an object of its own class is in a Box
a class, inlined as a list Vec<X>
a class, inlined as a dict HashMap<String, X>
any_of or exactly_one_of members with ranges an enum in the module of the class, such as measure_utl::value_range. The member ranges replace the range of the slot
a type with union_of an enum like the one for any_of, with a variant for each Rust type of the members
a slot with subproperty_of an enum of the slots it can hold, such as PredicateEnum, unless --expand-subproperty-of=false

An optional slot is an Option, and a multivalued slot a Vec.

Classes, enums and enum variants get PascalCase names, made the same way as in the other generators of ohi LinkML: named thing and NamedThing are NamedThing, HTTPRequest is HttpRequest, and ZERO_OR_ONE is ZeroOrOne. Slots and types keep their names, with _ for spaces and -, as in LinkML-Python: has part is has_part, and birthDate stays birthDate. A name that is a Rust keyword gets a trailing _, such as type_, and so does a slot named after a Python keyword, such as from_, as the Python bindings use the field names. The data keeps the slot name, or the alias of the slot, if it has one.

The generator reports an error for two classes or enums with the same Rust name.

With --python pyo3 or --python pyo3_stubs, the crate is a Python extension module, named after the crate. Build it with maturin develop or maturin build. Each struct is a Python class with a constructor. With pyo3_stubs, cargo run --bin stub_gen --features stubgen writes the Python type stubs (.pyi files) of the module, with pyo3-stub-gen, so that Python editors and type checkers know the classes.

With --handwritten-lib, the generated code is in src/generated/, and src/lib.rs is yours to change: it is only written when it doesn’t exist yet. It has a load_yaml_<tree root> function, also in Python.

As of 25 November 2026, ohi LinkML includes the fixes from currently open pull requests to LinkML-Python:

  • linkml/linkml#3662: an OrSubtype enum has a variant for the class itself.
  • linkml/linkml#3919 and linkml/linkml#4092: all Rust keywords and the Python keywords are escaped, and the data keeps the slot names.
  • linkml/linkml#4075: the crate name is checked, made from the schema name if unset, and names the Python module. The options stubgen and expand_subproperty_of.

Additionally, the following issues are fixed in ohi LinkML:

  • Class, enum and variant names are made as in the other generators of ohi LinkML, so two different names never get the same Rust name: a_1_2 is A1_2 and a_12 is A12, where LinkML-Python makes both A12. Names with capitals change too: HTTPRequest is HttpRequest and ZERO_OR_ONE is ZeroOrOne, where LinkML-Python keeps HTTPRequest and makes ZEROORONE.
  • Classes, fields and the variants of OrSubtype enums are ordered by rank and then by name, as in the other generators of ohi LinkML, instead of by their order in the schema files.
  • A type designator with a URI range picks a class by the URI or CURIE of its class_uri, as the LinkML specification says, and not also by a URI made from the class name.
  • The type aliases have the types of the fields: integer is i64, not String.
  • A slot with an alias is written under its alias, as in other LinkML tools.
  • An enum has its serde names without --serde too, and its variants have valid and unique names. An enum without permissible values is a String.
  • An enum of the ranges of a slot reads plain values, rather than {"i64": 3}, has one variant for each Rust type, and has the OrSubtype enum in the variant of a class with subclasses.
  • A value that contains its own class through a subclass is boxed.
  • A dict entry is written in the short form key: value only if no other field is set. A list inlined as a list is written as a list. A class with only a key can be inlined as a dict.
  • The getters of the traits compile for slots with different ranges in the descendants, boxed values, and slots of two mixins with the same name.
  • Generated impls don’t use names such as Self::Error, which a variant named Error hides.
  • A slot gets no type alias if another item has its name, such as a slot named date.
  • The crate version is the schema version only if it is a semantic version, as cargo requires.
  • The crate reads YAML with yaml_serde, as rust-linkml-core does, instead of serde_yml, which is unsound and no longer maintained (RUSTSEC-2025-0068).
  • Any class with the linkml:Any URI and no slots gets the struct for any value, not only a class named Anything.
  • A required multivalued slot must be in the data, and is always written, even when it is empty.
  • A multivalued slot with one value is written as a list, not as a single value.
  • An integer is an i64, which has the same size everywhere, instead of an isize.
  • A datetime is a DateTime<FixedOffset>, which keeps the offset, instead of a NaiveDateTime. With --date-type string, both are strings, and the crate doesn’t depend on chrono.
  • The crate depends on serde_json for the values of linkml:Any and for reading inlined classes, instead of serde-value, which is no longer maintained. It depends on yaml_serde only for the YAML loader of --handwritten-lib, and on serde_path_to_error only with PyO3.
  • The Python bindings are one option, python, instead of pyo3 and stubgen.
  • The code for serde, PyO3 and type stubs is generated only when its option is on, and Cargo.toml lists only the dependencies that the code uses.
  • Structs and enums get doc comments from the titles and descriptions in the schema.
  • Each struct has a new function that takes its required slots.
  • ifabsent is supported.
  • Enums derive Copy, Eq and Hash.
  • The slot type aliases are in a module slots, so they don’t crowd the top level of the crate.
  • decimal is an f64, and time a String.
  • The crate has all classes of the schema and its imports. There are no pruning options.