6
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

私的 Rust スタイルノート

Last updated at Posted at 2020-10-08

古い投稿です 🙇

リンク

[rust-analyzer/style.md]: https://github.com/rust-analyzer/rust-analyzer/blob/master/docs/dev/style.md)

スタイル

use 宣言

[rust-analyzer/style.md] を参考にします。

定数

const VALUE が推奨されています:

pub struct A;

impl A {
    pub const VALUE: u32 = 0;
}

命名

モジュール名は短くします:

  • mod gfx: graphics
  • mod geom2d: geometry 2D

型名は気分に応じて短くします:

  • mat: Mat3f
  • cam: Camera2D
  • vbuf: VertexBuffer

変数名・関数名はアイデアを尽くして短くします:

  • l2w: local 座標を world 座標へ変換
  • rcx: RenderContext

rcx は rustc の 命名規約 より

名前は複数形が自然になる形を好みます:

  • vtx vert, verts: vertices (頂点)

パッケージ名に関しては、 my-crate のようにハイフンを使うのが慣習でした。しかしライブラリ名は my_crate であり、コード上では my_crate と書きます。なので僕はパッケージ名も my_crate に統一します。

ブロックを積極的に式として使う

Tiled マップの読み込みを例に出します。雰囲気で読んでください 🙇

一次変数や mutable 変数のスコープの限定に使います:

let texture = {
    let relative_img_path = &tileset.images[0].source;
    let img_path = tiled_dir_path.join(relative_img_path);
    TextureData2d::from_path(device, &img_path).unwrap()
};

TilesetImageSpan {
    first_gid: tileset.first_gid,
    texture,
}

実はこのコードもさらに大きな式として書き直せます:

TilesetImageSpan {
    first_gid: tileset.first_gid,
    texure: {
         let relative_img_path = &tileset.images[0].source;
         let img_path = tiled_dir_path.join(relative_img_path);
         TextureData2d::from_path(device, &img_path).unwrap()
    },
}

やり過ぎるとフローが隠れるますので、好みの問題でしょうか……。

mod.rs vs module_name.rs

Rust 2018 以降は新しいモジュールの書き方が推奨されています。実際使ってみるとディレクトリ移動が減っていいなと思います。

メタ

サブクレート

crates ディレクトリに入れます。

ripgreprust-analyzer がそうしています。

よく使う外部クレート

などなど……

Infra doc

2020/11/18 から stable 版 cargo でも使用できます

[item](path/to/item) と書いてリンクを張れます:

/// [`path`](std::path), [`sub`](self::sub)
pub struct B;

mod sub {}

スコープ内のアイテムは、パス指定無しで自動的にリンクされます:

/// [`B`] is linked automatically!
pub struct A;

pub struct B;

パスは別の行から指定することもできます:

/// [`C`] is in module [`c`]. Links to [`C`] are supplied below:
///
/// [`C`]: self::c::C
struct X;

mod c {
    /// This is an [item in super module linked with an alias][alias]
    ///
    /// [alias]: super::X
    pub struct C;
}

ちなみに docstring:

/*!
This is a multi-line docstring comment!
*/

crates.io も nightly 版の cargo でドキュメント生成をしているので、積極的に使って大丈夫です。

以上

また何か気付いたら追記します。

6
4
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
6
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?