1

There's a crate I want to use as a library for some of my own code (speedtest-rs specifically, but it doesn't really matter). However, whenever I try to use this crate, the compiler doesn't want to play nice with it.

$ cargo build
   Compiling my-project v0.1.0 (/home/nick/Documents/code/my-project)
error[E0432]: unresolved import `speedtest_rs`
 --> src/main.rs:1:5
  |
1 | use speedtest_rs::*;
  |     ^^^^^^^^^^^^ use of undeclared type or module `speedtest_rs`

Looking at the Rust book, it seems like there's a distinction between a binary and library crae

The rand crate is a library crate which contains code intended to be used in other programs

Some googling has shown me that binary crates just have an extra link step, so I should be able to link against them, right? I know a lot of Rust packages have both a library and a binary in them, but what do you do when an author does not seem to follow this pattern?

ollien
  • 4,418
  • 9
  • 35
  • 58

1 Answers1

4

Some googling has shown me that binary crates just have an extra link step, so I should be able to link against them, right?

No. It's not that simple. Plus that extra step creates an executable file rather than a library file. An executable cannot be used as a library.

I know a lot of Rust packages have both a library and a binary in them, but what do you do when an author does not seem to follow this pattern?

You can:

  • Ask them on GitHub to publish a library.
  • Fork the crate and make your own library (which you can do since it is published with the usual dual “Apache License, Version 2.0” + “MIT” license).

There isn't an automated way to use a binary crate as a library because in particular:

  • Rust won't generate a library.
  • Since the crate is missing a src/lib.rs file, nothing is exported. This is akin to have all items in that crate private. You wouldn't be able to use anything.
mcarton
  • 27,633
  • 5
  • 85
  • 95
  • Such is life, I guess. This seems like a silly restriction on behalf of the compiler, but that's how things go, sometimes :/ – ollien Jul 26 '20 at 18:30
  • 4
    It's not a silly restriction, but a conscious choice: If the crate's author does not want to maintain a library, why should the compiler force them to? Publishing a library is much more constraining than publishing a binary. `cargo` however makes it super easy to publish both a library and binaries. – mcarton Jul 26 '20 at 18:39