LoginSignup
4
2

More than 5 years have passed since last update.

Rustのお勉強 - Cargoを使ってみる

Posted at

前回、Rustの実行環境をDockerで作るところまでやりました。RustにはCargoというパッケージマネージャーがあって、依存関係管理以外にもいろいろやってくれるようです。今回はCargoを使ってRustのお勉強ができるようにしていきたいと思います。

Cargoでプロジェクトを作る

前回rust-envという名前でイメージをビルドしたので、それを使ってコンテナに入ります。その後、cargoコマンドでプロジェクトを作ります。

$ docker run --rm -it -v $PWD/share:/share -w /share rust-env:latest
root@7b1f977a0c05:/share# cargo new --bin hello
error: Failed to create project `hello` at `/share/hello`

Caused by:
  could not determine the current user, please set $USER

エラー出ましたね。$USERをセットしろと言われています。ここでいろいろ調べましたが、コンテナ起動の際にホストの$USERをセットすればいいようです。/shareの中にはさっきのcargoコマンドでできた空のhelloディレクトリができているので事前に削除しておいて、コンテナを再起動します。

$ docker run --rm -e USER=$USER -it -v $PWD/share:/share -w /share rust-env:latest
root@4b713b34ecab:/share# echo $USER
mac側の$USER
root@4b713b34ecab:/share# cargo new --bin hello
     Created binary (application) `hello` project

できました。すでにファイルができているそうなので、コンパイルと実行が同時にできるcargo runしてみます。

root@4b713b34ecab:/share# cd hello/
root@4b713b34ecab:/share/hello# ls
Cargo.toml  src
root@4b713b34ecab:/share/hello# cargo run
   Compiling hello v0.1.0 (file:///share/hello)
    Finished dev [unoptimized + debuginfo] target(s) in 6.28s
     Running `target/debug/hello`
Hello, world!

できました。とりあえず勉強中にrustcでいちいちコンパイルする作業がこれで不要になりそうです。次からやっとrustそのものの勉強に入れます。

4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2