追加の制約なしの場合
やるだけ。 やろう。
#![allow(unused)] fn main() { // 値を作るメソッド。自明。 pub struct MyString(String); impl MyString { #[inline] #[must_use] pub fn new(s: String) -> Self { Self(s) } } }
ついでに、のちのちトレイト定義で使うための便利メソッドも用意しておこう。
#![allow(unused)] fn main() { // 所有権付きの型から所有権なしのスライス型への変換。のちのち便利。 #[repr(transparent)] pub struct MyStr(str); impl MyStr { fn new(s: &str) -> &Self { unimplemented!() } fn new_mut(s: &mut str) -> &mut Self { unimplemented!() } } pub struct MyString(String); impl MyString { #[inline] #[must_use] pub fn as_my_str(&self) -> &MyStr { MyStr::new(self.0.as_str()) } #[inline] #[must_use] pub fn as_my_str_mut(&mut self) -> &mut MyStr { MyStr::new_mut(self.0.as_mut_str()) } } }
もしこれらの作成や変換のメソッドをユーザに公開するつもりがなければ、 pub
でなくプライベートなメソッドにしておこう。
普通は (String::as_str()
がそうであるように) 公開してしまうものだと思うが、たとえば AsRef
や Deref
経由で変換を提供することもできるので、公開が必須というわけでもない。