3 ms·
The best part about Rust is the type system. For one example, in a web app I'm building for a client, we have two types to represent invoice ids: one for the i
by couchand 6y ago
The best part about Rust is the type system. For one example, in a web app I'm building for a client, we have two types to represent invoice ids: one for the invoice id that came back in a response from the API, and one for an invoice id that a user is asking for. They are distinct because we know that an InvoiceId refers to an actual invoice in the system, and a UnverifiedInvoiceId might not. Both of them are distinct from a CustomerId or any other id.
This might sound like it could get cumbersome fast, but it's actually really simple in practice, due to clever uses of traits. UnverifiedInvoiceId implements rocket::FromParam, so I can deserialize it from a URL parameter. InvoiceId is only created in the serde::Deserialize implementation of an invoice-returning API response.
So a (significantly simplified) endpoint in the app might look like:
#[get("/invoices/<unverified_invoice_id>")]
pub fn get_invoice_by_id(
unverified_invoice_id: UnverifiedInvoiceId,
api_conn: ApiConnection,
) -> HtmlResponse {
// API "search" methods take unverified user input as parameters
let invoice = api_conn.fetch_invoice_by_id(unverified_invoice_id);
// API "lookup" methods take verified ids
let line_items = api_conn.fetch_invoice_line_items(invoice.id);
render_invoice(invoice, line_items);
}
I can't accidentally switch up things that don't belong together, even though under the hood they're all just unsigned ints.
- nivethan 6y agoBusiness logic is where Rust would shine and rust feels nicer to work in than java.
- mavelikara 6y agoWouldn't Kotlin and Typescript provide many of these benefits on a much more mature ecosystem?
- oftenwrong 6y agoOne time I made an authentication system for an application that had some types like PlainTextAccountPassword and HashedAccountPassword. The storage backend for accounts accepted a HashedAccountPassword only. This way it would be less likely that a maintainer would end up storing a plain text password. It is possible to do something like this in nearly any language with a type system.
- stjohnswarts 6y agoYeah, easy to make a class for that in Python and you basically have a new type. It can even check itself, although I'm not sure that's a great idea :) .
- g_delgado14 6y agoNone of this is unique to Rust - I can do this in typescript: Serde -> Zod (https://github.com/vriad/zod https://github.com/vriad/zod) Diesel -> Prisma Yet you expose yourself to concepts that are unique to Rust that do not enhance the developer experience (such as lifetimes). I don't need to worry about lifetimes in typescript and can just focus on shipping code. Lifetimes is just one example, but there are others that create more friction than they provide benefit IMO.