You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Using a target of a deref coercion can increase the flexibility of your code when you are deciding which argument type to use for a function argument.
In this way, the function will accept more input types.
This is not limited to slice-able or fat pointer types. In fact you should always prefer using the __borrowed type__ over __borrowing the owned type__. E.g., `&str` over `&String`, `&[T]` over `&Vec<T>`, or `&T` over `&Box<T>`.
Using borrowed types you can avoid layers of indirection for those instances where the owned type already provides a layer of indirection. For instance, a `String` has a layer of indirection, so a `&String` will have two layers of indrection.
We can avoid this by using `&str` instead, and letting `&String` coerce to a `&str` whenever the function is invoked.
## Example
For this example, we will illustrate some differences for using `&String` as a function argument versus using a `&str`, but the ideas apply as well to using `&Vec<T>` versus using a `&[T]` or using a `&T` versus a `&Box<T>`.
Consider an example where we wish to determine if a word contains three consecutive vowels.
We don't need to own the string to determine this, so we will take a reference.
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Use coercion for arguments #29
Use coercion for arguments #29
Changes from all commits
302f5b4
3c12bc8
0a478cc
4aed435
a38e09e
03caded
d6b6986
86dcfd4
366db72
048c704
cd9fbf0
9c1a19b
bf45e6c
783e9fc
ad68802
252f8f1
4a05a94
012addb
66aed67
d06c86b
c9057b7
87985ca
e32db7d
268a6d3
303bdba
3b161c0
45360aa
136b9b0
88d418c
f2266ba
File filter
Filter by extension
Conversations
Jump to
There are no files selected for viewing