📝

Rust開発環境構築

2020/09/18に公開

Rust の開発環境構築

はじめに

最近、Rustをいろいろと触り始めたので、その際に行った環境構築について書きます。
普段から、vim を利用しているので、ここでは vim での環境構築を記載します。

Rust のインストール

公式に記載がある通り、以下のコマンドでインストール

curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

上記のコマンドで、rustc, rustup, cargo がインストールされる

cargo-edit

Cargo.toml にパッケージを追加する際に便利なサブコマンドをインストール

cargo install cargo-edit

これによって、cargo add, cargo list, cargo rm が利用できるようになる

cargo-watch

ファイルの変更をトリガーに、check や test を実行したいので、以下をインストール

cargo install cargo-watch

これによって、cargo watch -x test などが利用できるようになる

repl

Rust でも、python のような repl を使いたいときがあるのでインストール

cargo install evcxr_repl

これによって、evcxr コマンドで repl を起動できるようになる

vim 側の設定

以下の vim plugin をインストールしておく。ここでは dein.vim を利用する例を記載

  • prabirshrestha/vim-lsp
  • mattn/vim-lsp-settings
  • rust-lang/rust.vim
  • thinca/vim-quickrun

dein.toml

[[plugins]]
repo = 'prabirshrestha/vim-lsp'

[[plugins]]
repo = 'mattn/vim-lsp-settings'
hook_add = 'source ~/.vim/plugins/vim-lsp-settings.vim'

[[plugins]]
repo = 'rust-lang/rust.vim'
hook_add = 'source ~/.vim/plugins/rust.vim'

[[plugins]]
repo = 'thinca/vim-quickrun'
hook_add = 'source ~/.vim/plugins/vim-quickrun.vim'

vim-lsp-settings.vim

if empty(globpath(&rtp, 'autoload/lsp.vim'))
  finish
endif

function! s:on_lsp_buffer_enabled() abort
  setlocal omnifunc=lsp#complete
  setlocal signcolumn=yes
  nmap <buffer> gd <plug>(lsp-definition)
  nmap <buffer> <f2> <plug>(lsp-rename)
  inoremap <expr> <cr> pumvisible() ? "\<c-y>\<cr>" : "\<cr>"
endfunction

augroup lsp_install
  au!
  autocmd User lsp_buffer_enabled call s:on_lsp_buffer_enabled()
augroup END
command! LspDebug let lsp_log_verbose=1 | let lsp_log_file = expand('~/lsp.log')

let g:lsp_diagnostics_enabled = 1
let g:lsp_diagnostics_echo_cursor = 1
let g:asyncomplete_auto_popup = 1
let g:asyncomplete_auto_completeopt = 0
let g:asyncomplete_popup_delay = 2000
let g:lsp_text_edit_enabled = 1

rust.vim

let g:rustfmt_autosave = 1

vim-quickrun.vim

if !exists("g:quickrun_config")
  let g:quickrun_config={}
endif

let g:quickrun_config = {
  \  "_" : {
  \    "outputter": "popup",
  \  }
  \}

augroup rust_quickrun
  au!
  autocmd BufNewFile,BufRead *.rs let g:quickrun_config.rust = {'exec' : 'cargo run'}
augroup END

利用開始

適当なサンプルプロジェクトを作成

cargo new sample
vi sample/src/main.rs

ファイルを開いたら、vimの上から language server のインストール

:LspInstallServer

上記のインストールが済めば、vim の popup でfunctionの説明や、quickrun で cargo run の結果表示ができるようになります。

普段は、vim で Rust を書きつつ、簡単な動作確認は quickrun で行い、cargo コマンドを実行したい場合には、:bo terminal ++rows=20 などで terminal を起動して実行。
cargo watch をしたい場合は、素直に tmux で別 pane を開いて実行しておく
といったような使い方をしています。

Discussion