Hey there!
I recently started learning Rust and am currently digging into some common patterns, currently the Newtype pattern.
I've read that Rust has a much stronger type system than other languages, but I currently don't quite understand the practical benefits in some situations.
Say we have a struct User:
struct User {
name: String,
password: String,
}
If I wanted to differentiate the fields and give the password some special behavior, I could refactor it like this:
pub struct Password(String);
// impl goes here...
This makes sense to me conceptually, however I don't quite get the benefit the type system is giving me here, compared to some language like Java where I could do something such as this:
public class User {
private String name;
private Password password;
public User(String name, String password) {
this.name = name;
this.password = new Password(password);
}
}
public class Password {
private String value;
public Password(String value) {
this.value = value;
}
// methods go here
}
In both cases, I can encapsulate special behavior for Password
. What specific advantages does the Rust type system give me here that a language like Java wouldn’t?
Thanks in advance!