{
  "path": "/return-type-based-dispatch.html",
  "site": "at://did:plc:x67qh7v3fd7znbdhauc45ng3/site.standard.publication/3mjcd2t6afe25",
  "$type": "site.standard.document",
  "title": "Return-type based dispatch",
  "updatedAt": "2020-03-03T00:00:00.000Z",
  "publishedAt": "2020-03-03T00:00:00.000Z",
  "textContent": "One surprising feature of type inference in languages like Rust\nis defining functions with generic return types.\nThe idea is that by specifying at some later point in the code\nwhich type you want your function to return,\nthe compiler can go back and fill in the blanks.\n\nFor example, let's have a look at this function:\n\nYou pick the output\n\nIt has no value parameters, but one type parameter, T.\nThat T is its return type and also used in the function body.\nYou can call it like so:\n\nOr, being explicit about the type parameter, like this:\n\nThis is quite neat!\n\nMore generic: collect\n\nA promising way to be more generic in Rust\nis to use more traits!\nHave a look at how the [Iterator::collect] method is defined:\n\nYou can read this type signature as\n\n> Consume self and return something\n> of a type that implements can be made From [an] Iterator\n> for the type of items we are iterating over.\n\nLike above,\nwe call this by specifying what kind of output type want.\n[Looking][FromIterator implementors] at some of the types FromIterator is implemented for\nis pretty revealing of the use cases.\nYou can get:\n\n- a Vec by collecting any items,\n- a BTreeMap or HashMap by collecting tuples,\n- but also PathBuf by collecting Paths,\n- and String for strings and string slices.\n\nNote: All these types are what you might call \"container\" types.\n\nOne more for the road\n\n> More generic? More traits.\n\nThere is one more gem hidden in FromIterator:\n\nThis means:\nYou can construct a [Result] containing\nany type of container of items A\nby collecting items that are Results of type A.\n(The first Err will make the outer Result be an Err.)\nHere's an example, see [the docs][FromIterator for Result] for another one:\n\nNote: If you like type theory:\nWhat we're building is a Result<<T<A>, E>>\nby collecting Result<A, E>s and specifying T.\n\n[Iterator::collect]: https://doc.rust-lang.org/1.41.1/std/iter/trait.Iterator.html#method.collect\n[FromIterator implementors]: https://doc.rust-lang.org/1.41.1/std/iter/trait.FromIterator.html#implementors\n[Result]: https://doc.rust-lang.org/1.41.1/std/result/enum.Result.html\n[FromIterator for Result]: https://doc.rust-lang.org/1.41.1/std/iter/trait.FromIterator.html#method.from_iter-14",
  "canonicalUrl": "https://deterministic.space/return-type-based-dispatch.html"
}