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
chronofor 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_stubsalso adds the code for Python type stubs. In a crate, this code is behind the Cargo featuresserde,pyo3andstubgen, which are on by default and bring their dependencies. A single.rsfile has no features, see One file.
ohi get w3c/prov-oohi linkml to rust --crate-name prov prov-o.linkml.yamlimport ohi_linkml
with ohi_linkml.load_file("prov-o.linkml.yaml") as schema: files = schema.rust(crate_name="prov")import { readFileSync } from "node:fs";import { LinkML } from "@neverblink/linkml";
const yaml = readFileSync("prov-o.linkml.yaml", "utf8");const { view, report } = LinkML.loadFromString(yaml, {});if (!view) throw new Error(JSON.stringify(report));const files = view.rust({ crate_name: "prov" });use ohi_linkml::{load_file, RustGeneratorOptions};
let schema = load_file("prov-o.linkml.yaml", &Default::default())?;let files = schema.rust(&RustGeneratorOptions { crate_name: Some("prov".to_owned()), ..Default::default()})?;#include <stddef.h>#include "ohi_linkml.h"
char *report = NULL, *error = NULL;long long schema = linkml_load_file("prov-o.linkml.yaml", NULL, &report, &error);char *files = linkml_rust(schema, "{\"crate_name\": \"prov\"}", &error);linkml_free(files);linkml_free(report);linkml_free(error);linkml_close(schema);import eu.neverblink.linkml.generator.options.RustGeneratorOptionsimport eu.neverblink.linkml.generator.rust.RustGeneratorimport eu.neverblink.linkml.schemaview.{SchemaIssues, SchemaView}
val loaded = SchemaView.loadSchemaViewFromUri("prov-o.linkml.yaml")given SchemaView = SchemaIssues.orThrow(loaded)val files = RustGenerator().generateFiles( RustGeneratorOptions(crateName = Some("prov")),)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.
One file
Section titled “One file”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.rspub use model::{Zoo, Animal, Keeper};Options
Section titled “Options”crate_namestring--crate-nameScala crateNameThe 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--date-typeScala dateTypeThe Rust types for date and datetime values.
chronochrono::NaiveDateandchrono::DateTime<FixedOffset>. Adatetimemust have an offset, as in RFC 3339 and JSON Schema.stringString, with the text from the data, unchanged and unchecked. The crate doesn't depend on chrono.
expand_subproperty_ofbooleandefault true--expand-subproperty-ofScala expandSubpropertyOfWhether 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--handwritten-libScala handwrittenLibWhether 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--metadata-languageScala metadataLanguageThe language of the titles and descriptions in the output, for schemas with text in more than one language.
pythonRustPythondefault none--pythonWhich Python bindings to generate. PyO3 needs the serde code, so pyo3 and pyo3_stubs also generate it.
noneNo Python bindings.pyo3Python classes for the structs, made with PyO3. The crate is a Python extension module, with a#[pymodule]function and apyproject.tomlthat builds it with maturin. In a crate, this code is behind thepyo3feature, which is on by default.pyo3_stubsThe same aspyo3, plus the code for the Python type stubs (.pyifiles) of the module, made with pyo3-stub-gen. In a crate, this code is behind thestubgenfeature, and comes with astub_genprogram that writes the stubs.
serdebooleandefault true--serdeWhether 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.
Loading and dumping data
Section titled “Loading and dumping data”With the serde feature, any serde format works, such as YAML:
let zoo: Zoo = yaml_serde::from_str(&text)?; // loadlet text = yaml_serde::to_string(&zoo)?; // dumpLoading 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.
Example
Section titled “Example”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: Shiftenums: 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.
How the schema maps to Rust
Section titled “How the schema maps to Rust”Classes
Section titled “Classes”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.
Traits
Section titled “Traits”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.
Slot types
Section titled “Slot types”| 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.
Python bindings
Section titled “Python bindings”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.
Differences from LinkML-Python
Section titled “Differences from LinkML-Python”As of 25 November 2026, ohi LinkML includes the fixes from currently open pull requests to LinkML-Python:
- linkml/linkml#3662: an
OrSubtypeenum 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
stubgenandexpand_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_2isA1_2anda_12isA12, where LinkML-Python makes bothA12. Names with capitals change too:HTTPRequestisHttpRequestandZERO_OR_ONEisZeroOrOne, where LinkML-Python keepsHTTPRequestand makesZEROORONE. - Classes, fields and the variants of
OrSubtypeenums are ordered byrankand 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:
integerisi64, notString. - A slot with an
aliasis written under its alias, as in other LinkML tools. - An enum has its serde names without
--serdetoo, and its variants have valid and unique names. An enum without permissible values is aString. - An enum of the ranges of a slot reads plain values, rather than
{"i64": 3}, has one variant for each Rust type, and has theOrSubtypeenum 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: valueonly 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 namedErrorhides. - 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 ofserde_yml, which is unsound and no longer maintained (RUSTSEC-2025-0068). - Any class with the
linkml:AnyURI and no slots gets the struct for any value, not only a class namedAnything. - 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
integeris ani64, which has the same size everywhere, instead of anisize. - A
datetimeis aDateTime<FixedOffset>, which keeps the offset, instead of aNaiveDateTime. With--date-type string, both are strings, and the crate doesn’t depend on chrono. - The crate depends on
serde_jsonfor the values oflinkml:Anyand for reading inlined classes, instead ofserde-value, which is no longer maintained. It depends onyaml_serdeonly for the YAML loader of--handwritten-lib, and onserde_path_to_erroronly with PyO3. - The Python bindings are one option,
python, instead ofpyo3andstubgen. - The code for serde, PyO3 and type stubs is generated only when its option is on, and
Cargo.tomllists 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
newfunction that takes its required slots. ifabsentis supported.- Enums derive
Copy,EqandHash. - The slot type aliases are in a module
slots, so they don’t crowd the top level of the crate.
Limitations
Section titled “Limitations”decimalis anf64, andtimeaString.- The crate has all classes of the schema and its imports. There are no pruning options.