Adapting examples for a new crate

Friends

Is there a generic procedure for adapting example code from the examples directory in a crate into a stand alone crate?

Specifically the application example from winit is the only Rust code I have found that will open a window on my Raspberry Pi and its tiny screen.

Naively copying examples/application.rs to main.rs in a new crate, and copying all the dependencies from winit/Cargo.toml has not come close to working.

I am wondering if there is a more general methodological method that I do not know.

It looks like you have hit a common mistake when trying to use Rust examples: copying code from the latest development version on GitHub, which is not compatible with the latest published version on crates.io.

The easiest place to find published source is docs.rs, e.g. https://docs.rs/crate/winit/0.30.11/source/examples/, and I see no example named application.rs so I can conclude that the examples must have substantially changed. (But they might have changed even without changing any names, too.) You should take example code from there — or more generally, from the same version you're using, whether you get it from docs.rs or GitHub (e.g. https://github.com/rust-windowing/winit/tree/v0.30.11/examples).

1 Like

Excellent!

In my Cargo.toml when I specify winit I should specify the git repository if I am using an example from the git repository.

I should get the examples from docs.rs if using Crates.io.

Looking around at various docs.rs pages for random crates, I cannot find the generic way to find examples. Even comparing the "source" on docs.rs to the repositories.

Is that on a crate by crate basis or have I missed something there too?

Ah, another catch! There are actually two different “source” views on docs.rs:

  • The rustdoc source view, found via links in the documentation. This view contains only the source files of the library crate itself — the files that you are reading the documentation of.
  • The docs.rs source view, found via the docs.rs top bar or crate page. This view contains all of the files in the entire package. This is the one you need to find examples.

Also, some publishers may choose to omit examples from what they publish to crates.io even if they have examples in their repository. (This is either because they feel publishing examples is wasted disk space since almost nothing uses them there, or because the examples are actually separate packages.) In that case, you have to find the examples their repository, and make sure to select the right version tag.

3 Likes