Skip to content

Commit

Permalink
Add const_new to create compile-time constants (#60)
Browse files Browse the repository at this point in the history
  • Loading branch information
yunjhongwu committed Mar 1, 2024
1 parent d1af226 commit 8d6af97
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 1 deletion.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ use strong_type::StrongType;
struct Tag(String);

let tag = Tag::new("dev");
const TAG: Tag = Tag::const_new("prod");
```

#### Demonstrating type distinctiveness:
Expand Down
5 changes: 4 additions & 1 deletion strong-type-derive/src/detail/basic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,15 @@ pub(crate) fn implement_basic(
pub fn new(value: impl Into<#value_type>) -> Self {
Self(value.into())
}

pub const fn const_new(value: #value_type) -> Self {
Self(value)
}
}

impl StrongType for #name {
type UnderlyingType = #value_type;
type PrimitiveType = #primitive_type;

}

impl std::fmt::Debug for #name {
Expand Down
10 changes: 10 additions & 0 deletions strong-type-tests/tests/strong_type.rs
Original file line number Diff line number Diff line change
Expand Up @@ -263,4 +263,14 @@ mod tests {
}
}
}

#[test]
fn test_const() {
#[derive(StrongType)]
struct NamedI32(i32);

const NAMED_I32: NamedI32 = NamedI32::const_new(1);

assert_eq!(NAMED_I32, NamedI32::new(1));
}
}

0 comments on commit 8d6af97

Please sign in to comment.