スライス型の定義

型定義の時点では、追加の制約の有無は基本的に関係ない1

追加の制約なしのスライス型:


#![allow(unused)]
fn main() {
/// My custom string slice type.
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(transparent)]
// Comparisons implemented for the type are consistent (at least it is intended to be so).
// See <https://github.com/rust-lang/rust-clippy/issues/2025>.
#[allow(clippy::derive_hash_xor_eq, clippy::derive_ord_xor_partial_ord)]
pub struct MyStr(str);
}

追加の制約付きのスライス型:


#![allow(unused)]
fn main() {
/// ASCII string slice type.
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(transparent)]
// Comparisons implemented for the type are consistent (at least it is intended to be so).
// See <https://github.com/rust-lang/rust-clippy/issues/2025>.
#[allow(clippy::derive_hash_xor_eq, clippy::derive_ord_xor_partial_ord)]
pub struct AsciiStr(str);
}

追加の制約付きのスライス型の別の例:


#![allow(unused)]
fn main() {
/// ASCII bytes slice type.
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(transparent)]
// Comparisons implemented for the type are consistent (at least it is intended to be so).
// See <https://github.com/rust-lang/rust-clippy/issues/2025>.
#[allow(clippy::derive_hash_xor_eq, clippy::derive_ord_xor_partial_ord)]
pub struct AsciiBytes(str);
}

AsciiStr と AsciiBytes の違いは、前者が文字列との相互運用のみを前提とする単純な実装で、後者は文字列のみならずバイト列との相互変換などが扱える点である。 利便性で考えれば後者が良いが、実装が若干煩雑になる箇所もある。 よって、本書では単純な実装で誤魔化すことも複雑な実装もできるよう、両方のコード例を提示する。


1

たとえばその追加の制約 (典型的には文法) を型パラメータとして与えるなどを考えると、定義の段階である程度の設計の調整が必要になるが、それは別の節で説明する (かもしれない)。