Traits
Traits name behavior that generic code can require.
Standard Traits
Standard traits include Stringable, Equatable, Orderable, and numeric operator traits.
traits.brp
text: String = 42.to_string()Bounds
A bound such as T: Orderable lets a generic function use ordering operations.
bounds.brp
pure func larger[T: Orderable](a: T, b: T) -> T:
if a > b:
a
else:
bOperator Traits
Operators are available when the type implements the required trait.
operators.brp
pure func add_pair[T: Addable](a: T, b: T) -> T:
a + bImplementing Traits
An implements block provides trait functions for a type.
impl.brp
implements Stringable for User:
pure func to_string(user: User) -> String:
user.nameExample
users.brp
record User {name: String, score: Int}
implements Stringable for User:
pure func to_string(user: User) -> String:
user.name + ": " + user.score.to_string()
pure func larger[T:Orderable](a: T, b: T) -> T:
if a > b:
a
else:
b
func main(args: List[String]) -> Void:
users: List[User] = [{name = "Ada", score = 91}]
match users.get(0):
Some(user): print(user.to_string())
None: print("no users")
Try It
terminal
blorp run users.brp