Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
958 views
in Technique[技术] by (71.8m points)

rust - Can I install a library using Cargo without a Cargo.toml?

I am going through Rust's getting started and I need to get the rand crate on my system. I'm not doing the Cargo packaging stuff (e.g. creating Cargo.toml) because I was interested in the language, not packaging.

Can I install the rand library on my system without creating a Cargo.toml using the cargo command?

$ cargo install rand
    Updating registry `https://github.com/rust-lang/crates.io-index`
specified package has no binaries
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Practical answer

No. Use Cargo. It's extremely easy to use and it prevents you from shooting yourself in the foot with managing versions (and conflicting versions).

because I was interested in the language, not packaging.

From the point-of-view of 99.9% of Rust users, Cargo is part of the language, or at least part of the Rust ecosystem. Many things are provided in crates that you might expect in another languages standard library (random number generation is a great example).

install the library on my system

Ultimately, this doesn't make sense. There's no One True Version of a library that you can install. Every program that uses a crate may use a different version because it has different needs. Even further, you may compile a crate in a different manner for different projects - crates have features that change how they may be compiled.

cargo install rand

This is actually a way to use Cargo to build an entire Rust project that provides a binary and install it on your system. This makes more sense as it's a single, contained entity. Unfortunately, it can be confusing for just this very reason!

See also:

Technically correct answer

Of course you can; you just have to do everything that Cargo does for you by hand. That involves

  1. Downloading the package.
  2. This also means any dependencies of the package.
  3. And the correct versions.
  4. Compile the package.
  5. And the dependencies.
  6. Maintaining the tree of dependencies and passing it to each subsequent package.
  7. Finally, you can compile your code.

A concrete example of compiling a single library and a single executable using that library:

$ rustc --edition=2018 --crate-type=rlib --crate-name library_example src/lib.rs -o libmy_library.rlib
$ rustc --edition=2018 --extern library_example=libmy_library.rlib examples/main.rs

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...