dimanche 2 avril 2023

Is it idiomatic to use impl TryInto

Let's say I want to make a function that adds two numbers, but it only works when they are between 1 and 3. To ensure this I can use type driven design and make a datatype SpecialI32 that meets these requirements.

The trait TryInto seems like a good fit. But the question is, should I do the conversion inside or outside the function?


struct SpecialI32 { ... }

// example 1
let sum = add(foo, bar).unwrap();

// example 2
let sum = add(foo.try_into().unwrap(), bar.try_into().unwrap());

I feel like this is a hard compromise.

example 1

  • easier to read
  • easier to use
    • user can get it right almost by accident

example 2

  • avoid unecessary bounds checks
    • when the user already has the right type
  • is type driven
    • the user cannot pass wrong parameter
  • avoids docs with abstract types
    • can be confusing
    • types can have a lot of trait implementation to look through

What is most common or recommended?

Aucun commentaire:

Enregistrer un commentaire