A rust newtype macro inspired by kotlin's inline class.
When we use
rust
newtype!(NewTypeOne, u32);
It generate the struct
```
struct UserHomeDirectory {
pub v: u32,
}
for you.
The ***v*** is the default public field.
rust
use inlinenewtype::newtype;
use std::path::PathBuf;
newtype!(UserHomeDirectory, PathBuf);
newtype!(UserRuntimeDirectory, PathBuf);
let userhomedirectory = UserHomeDirectory { v: PathBuf::from("hello") };
let userruntimedirectory= UserRuntimeDirectory {v: PathBuf::from("hello")};
fn testnewtypetypefunc(userhomedirectory: UserHomeDirectory) -> UserHomeDirectory{
userhomedirectory
}
compilefail
testnewtypetypefunc(userruntimedirectory); // mismatch type
You can aslo make the newtype public just adding the pub.
rust
use inlinenewtype::newtype;
use std::path::PathBuf;
newtype!(UserHomeDirectory, PathBuf, pub);
You also can change the field name if you want.
rust
use inlinenewtype::newtype;
use std::path::PathBuf;
newtype!(UserHomeDirectory, PathBuf, pathbuf);
let userhomedirectory = UserHomeDirectory { pathbuf: PathBuf::from("hello")};
asserteq!(userhomedirectory.pathbuf, PathBuf::from("hello"));
Transform from one newtype to another
rust
use inlinenewtype::newtype;
use std::path::PathBuf;
newtype!(UserHomeDirectory, PathBuf);
newtype!(UserRuntimeDirectory, PathBuf);
let userhomedirectory = UserHomeDirectory { v: PathBuf::from("hello") };
let userruntimedirectory = UserRuntimeDirectory { v: PathBuf::from("hello") };
fn transformuserhometoruntimedirectory(
mut userhomedirectory: UserHomeDirectory,
) -> UserRuntimeDirectory {
let mut runtimedir = userhomedirectory.v;
runtimedir.push("runtimedir");
UserRuntimeDirectory { v: runtimedir }
}
You can also using braces to declare the newtype.
rust
use inlinenewtype::newtype;
use std::path::PathBuf;
newtype! {UserHomeDirectory, PathBuf, pathbuf}
let userhomedirectory = UserHomeDirectory { pathbuf: PathBuf::from("hello") };
asserteq!(userhomedirectory.path_buf, PathBuf::from("hello"))
```