Rust Tip - Into String as Function Arguments
Here is a quick Rust Programming tutorial showing how to type function arguments to accept &str, &String, and String (which will be moved). This is useful when the body of the function needs the full String no matter what is passed.
Help support this channel: https://patreon.com/jeremychone
- When &str or &String is passed as an argument, new string allocation occurs on .into()
- When String is passed, no new allocation occurs on .into(). The String is moved to the function.
So, in a way, this technique gives allocation control to the caller.
Notes for this pattern:
1. Do not use this pattern if the function body does not need to own the String, and can get away &String or &str. Use &str in this case.
2. Some might think this pattern makes necessary allocation, but this is not the case (see video and points above). It is allocated only in the case of &str or &String are passed (which would have been anyway), and not if String is passed. The caaller has the control.
3 Downsides:
3.1 Binary size: As noted in a great comment from @JeffHanke below, the compiler will duplicate the function for each unique type passed (monomorphization). See (and vote) the comment for the binary size mitigation. For most app code, the cost should be negligible, moreover, if mitigated, compared to the ergonomic value (watch out for compiler inlining, but this can be mitigated as well). For embedded programming, this needs a little bit more scrutiny, as many other aspects of the code design anyway.
3.2 Function ergonomics could be a discussion, but it is subjective. I personally like this pattern as the method signature is clear, flexible, and efficient, as allocation will only occur if needed. But do what works for you and your team.
3.3 Unnecessary discussions about unnecessary allocations (see point 2 above).
Related external resources:
- https://www.philipdaniels.com/blog/2019/rust-api-design/ (Scroll down to Into section)
- https://rust-lang.github.io/api-guidelines/flexibility.htm #caller-decides-where-to-copy-and-place-data-c-caller-control (more generic but related "caller-decides" topic, see generic paragraphs)
Related external resources:
- https://www.philipdaniels.com/blog/2019/rust-api-design/ (Scroll down to Into section)
- https://rust-lang.github.io/api-guidelines/flexibility.htm #caller-decides-where-to-copy-and-place-data-c-caller-control (more generic but related "caller-decides" topic, see generic paragraphs)
Jeremy Chone:
- Twitter - https://twitter.com/jeremychone
- Discord On Rust - https://discord.gg/W2besKCzjx
- AWESOME-APP - https://awesomeapp.dev - Rust Templates for building awesome applications.
- Patreon - https://patreon.com/jeremychone - Any help is a big help (for Rust educational content)
Other popular Rust Programming videos:
- Quick Start Code Layout - https://www.youtube.com/watch?v=oxx7MmN4Ib0&list=PL7r-PXl6ZPcCIOFaL7nVHXZvBmHNhrh_Q
- AWESOME-APP Full Overview - Rust template for building Awesome Desktop Application: https://www.youtube.com/watch?v=BY_ZjPGqJJk&list=PL7r-PXl6ZPcCIOFaL7nVHXZvBmHNhrh_Q
- Tauri Quick Introduction (Desktop App wit Rust Programming): https://www.youtube.com/watch?v=kRoGYgAuZQE&list=PL7r-PXl6ZPcCIOFaL7nVHXZvBmHNhrh_Q
- Rust Web App tutorials series: https://www.youtube.com/watch?v=VIig9IcQ-w8&list=PL7r-PXl6ZPcCIOFaL7nVHXZvBmHNhrh_Q&list=PL7r-PXl6ZPcCLvwpdD2Vj1O4CyoFTiHKd
- Rust Bevy Full Tutorial - Game Development with Rust: https://www.youtube.com/watch?v=j7qHwb7geIM&list=PL7r-PXl6ZPcCIOFaL7nVHXZvBmHNhrh_Q
- Rust for Java Developers series: https://www.youtube.com/watch?v=iFdh4sPC5Tg&list=PL7r-PXl6ZPcD63DS2djSiz4SlXkaTfobc&index=2&t=654s
Playlists:
- Rust For Desktop App: https://youtube.com/playlist?list=PL7r-PXl6ZPcAQAi1lfVrtHCSbaJbwZ4O8
- Everything Rust Programming - Tutorials, Courses, Tips, Examples: https://youtube.com/playlist?list=PL7r-PXl6ZPcCIOFaL7nVHXZvBmHNhrh_Q
- Rust Programming for Web Development: https://youtube.com/playlist?list=PL7r-PXl6ZPcCLvwpdD2Vj1O4CyoFTiHKd
- Rust Courses: https://youtube.com/playlist?list=PL7r-PXl6ZPcB4jn1_VR3D8tSK9DxOaiQE
- Furst for Java Developers: https://youtube.com/playlist?list=PL7r-PXl6ZPcD63DS2djSiz4SlXkaTfobc
AWESOME-APP ➜ https://awesomeapp.dev - Rust Templates for building awesome applications.
Rust AWESOME-APP GitHub - https://github.com/orgs/rust-awesome-app/repositories
Other notes:
- Tool used to do the green lines. ScreenBrush on Mac App Store (Gromit seems to be the equivalent on Linux)
- Edited with Davinci Resolve.
#rustprogramming #tutorial #rustlangn
Что делает видео по-настоящему запоминающимся? Наверное, та самая атмосфера, которая заставляет забыть о времени. Когда вы заходите на RUVIDEO, чтобы посмотреть онлайн «Rust Tip - Into String as Function Arguments», вы рассчитываете на нечто большее, чем просто загрузку плеера. И мы это понимаем. Контент такого уровня заслуживает того, чтобы его смотрели в HD 1080, без дрожания картинки и бесконечного буферизации.
Честно говоря, Rutube сегодня — это кладезь уникальных находок, которые часто теряются в общем шуме. Мы же вытаскиваем на поверхность самое интересное. Будь то динамичный экшн, глубокий разбор темы от любимого автора или просто уютное видео для настроения — всё это доступно здесь бесплатно и без лишних формальностей. Никаких «заполните анкету, чтобы продолжить». Только вы, ваш экран и качественный поток.
Если вас зацепило это видео, не забудьте взглянуть на похожие материалы в блоке справа. Мы откалибровали наши алгоритмы так, чтобы они подбирали контент не просто «по тегам», а по настроению и смыслу. Ведь в конечном итоге, онлайн-кинотеатр — это не склад файлов, а место, где каждый вечер можно найти свою историю. Приятного вам отдыха на RUVIDEO!
Видео взято из открытых источников Rutube. Если вы правообладатель, обратитесь к первоисточнику.