Understanding Rust Closures aka. Anonymous Functions 🦀 💻

  Рет қаралды 9,655

Trevor Sullivan

Trevor Sullivan

9 ай бұрын

Like many other programming languages, Rust supports the concept of anonymous functions. In Rust, we call them "closures." Functions can be passed around, just like other data types. Rust closures have some unique functionality, however, that can trip you up while coding.
For example, Rust closure declarations use a different syntax than functions. Declaring input parameter data types for Rust closures is optional, not mandatory as with named functions. The Rust compiler is "smart" enough to figure out what data types to use for closure signature, based on your invocation of the closure. Using curly braces to surround the body of a Rust closure is also not required. Finally, borrowing mutable values in Rust closures requires that you declare the closure as mutable.
Closures are an interesting feature in Rust, and it's important that you understand exactly how they work!
🤯 Rust Programming Playlist 🦀 • Rust Programming Tutor...
📖 Rust Closures: doc.rust-lang.org/book/ch13-0...
Visual Studio Code ➡️ code.visualstudio.com
Rust Website ➡️ rust-lang.org
Rustup Installer ➡️ rustup.rs
Rust Docs ➡️ doc.rust-lang.org/book
Please follow me on these other social channels!
➡️ trevorsullivan.net
➡️ github.com/pcgeek86
➡️ / pcgeek86
➡️ / trevorsullivan
➡️ / trevorsoftware
➡️ tiktok.com/pcgeek86
All trademarks, logos and brand names are the property of their respective owners. All company, product and service names used in this website are for identification purposes only. Use of these names,trademarks and brands does not imply endorsement.
#opensource #software #linux #devops #programming #rusty #rustdev #dev #coding #codinglife #code #coder #ubuntu #ubuntulinux #appdev #rustlang #rust #developer

Пікірлер: 53
@TrevorSullivan
@TrevorSullivan 9 ай бұрын
Check out the full Rust programming playlist! 🦀 kzfaq.info/sun/PLDbRgZ0OOEpUkWDGqp91ODn0dk7LPBAUL
@adamszalkowski8226
@adamszalkowski8226 2 ай бұрын
Would have loved to see in this video concepts like `Fn`, `FnOnce`, when to use `move`, and function items vs pointers vs fn traits.
@kevinkkirimii
@kevinkkirimii 4 ай бұрын
The quality of your camera and the mic is sick and your tutorials are brilliant. Well done.
@TrevorSullivan
@TrevorSullivan 4 ай бұрын
Wow, thank you!! I'm glad you are learning from my channel!
@simonkalu
@simonkalu 2 ай бұрын
The best Rust closure tutorial on KZfaq. Well done, Trevor!
@TrevorSullivan
@TrevorSullivan 2 ай бұрын
Thank you Simon! I hope you're enjoying the Rust language! 🦀
@AnkurDwivedi-wx9kh
@AnkurDwivedi-wx9kh 3 күн бұрын
@28.00 for who do not understand println macro itself takes immutable reference of value it is supposed to print. hence the error
@kinositajona
@kinositajona 2 ай бұрын
The IDE filling in phantom types with a similar font and color to the rest of the text was hard to read. add(x: -3, y: -5); gave me an error lol. Maybe keep them off by default and flash them with a hotkey when you want to show what Rust is seeing?
@TrevorSullivan
@TrevorSullivan 2 ай бұрын
Hmmm I'll have to see if that's possible with the Rust Analyzer extension!
@mikemardis
@mikemardis 2 ай бұрын
Like the way you cover the material, thanks. Disappointed not to find a video on the second half of the chapter in the Rust book, though. Are you planning on doing iterators?
@TrevorSullivan
@TrevorSullivan 2 ай бұрын
Thanks for the comment! I have a video on Rust iterators. Were you looking for something else?
@mohsan5491
@mohsan5491 2 ай бұрын
Hey Trevor, Thanks a ton for this Rust course playlist! Your effort truly shows in the high quality content. It's made learning Rust much clearer and enjoyable. Really appreciate your work.
@TrevorSullivan
@TrevorSullivan 2 ай бұрын
Thank you! I appreciate your kind comment and I'm very happy that this has helped you. That's all I hope to accomplish, making other people's lives better, by sharing knowledge. I hope you benefit from viewing code in crisp 4k. 😊
@aar021
@aar021 8 ай бұрын
And I finally got closures
@TrevorSullivan
@TrevorSullivan 8 ай бұрын
Nice!!! They're not hard after all, right? 🙂🦀
@jakubrembiasz8942
@jakubrembiasz8942 7 ай бұрын
Very well explained. Thank you so much❤
@kelownatechkid
@kelownatechkid 3 ай бұрын
Really straightforward, great video!
@vonmakeheat
@vonmakeheat 6 ай бұрын
bro im over here nesting closures inside modules .... You are a great tutor Please Dont Stop Making theese videos !!!!
@ZeroCadence
@ZeroCadence Ай бұрын
Thank you. It’s a tough language to wrap your head around
@mohsan5491
@mohsan5491 2 ай бұрын
// In VSCode, type inference for a closure looks like this: let print_number: impl Fn(u16) = |n: u16| println!("incoming: {0}", n); // However, in RustRover, the inferred type for the same closure is presented as: let print_number: fn(u16) = |n: u16| println!("incoming: {0}", n); Interesting how different IDEs handle Rust's type inference for closures. VSCode uses impl Fn(u16) to indicate a flexible closure that might capture the environment, while RustRover opts for fn(u16), suggesting a simpler, non-capturing function pointer. It's a neat insight into the nuances of Rust's type system and how tooling can vary in presenting it.
@mohsan5491
@mohsan5491 2 ай бұрын
when I tried to expicitly type "let print_number : impl Fn(u16)=" analyser did not complained but compiler threw this error error[E0562]: `impl Trait` is not allowed in the type of variable bindings --> src/closures.rs:2:24 | 2 | let print_number : impl Fn(u16) = |n: u16| println!("incoming: {0}", n); | ^^^^^^^^^^^^ | = note: `impl Trait` is only allowed in arguments and return types of functions and methods
@TrevorSullivan
@TrevorSullivan 2 ай бұрын
That's interesting! Thanks for sharing.
@maguilecutty
@maguilecutty 5 ай бұрын
Another banger thanks sgain !!!
@lutfiikbalmajid
@lutfiikbalmajid 4 ай бұрын
Thanks, your tutorial is easy to understand
@piyushpatil6874
@piyushpatil6874 2 ай бұрын
Really Good Explanation !
@himerrokowoy3193
@himerrokowoy3193 6 ай бұрын
Brilliant content, thank you!
@j-p-d-e-v
@j-p-d-e-v 4 ай бұрын
Loved the tutorial
@benjaminpowell1508
@benjaminpowell1508 3 ай бұрын
Trevor, I'm new to Rust and your videos have really helped, thank you. I was just wondering what VS setting you have enabled to get the errors/warnings to show up inline. I think this would be helpful. Thanks!
@TrevorSullivan
@TrevorSullivan 3 ай бұрын
Hey Benjamin, thank you for joining me on the Rust journey! I have a video in the playlist that talks about setting up the Rust development environment. You'll want to install the Rust Analyzer extension for VScode. Keep on learning! 🚀
@benjaminpowell1508
@benjaminpowell1508 3 ай бұрын
@@TrevorSullivan Thanks, I'll check that out!
@user-gx8oe8zu4v
@user-gx8oe8zu4v Ай бұрын
Well explained
@anjonsarker2374
@anjonsarker2374 9 ай бұрын
Fantastic
@piotao
@piotao 4 ай бұрын
Hmm, very nice explanation, but there is perhaps more to be said in this interesting subject. What about function generator with closured variables? What about counters... randomizers... mixers.... and what is FnOnce ??? I think we all would love to see what you can tell about those topics. Closures are quite advanced tbh, but well, that's the time to learn I guess! :)
@abdushakoor0099
@abdushakoor0099 2 ай бұрын
clear, concise, amazing
@TrevorSullivan
@TrevorSullivan 2 ай бұрын
@abdushakoor0099 Thank you for your kind comment! What other Rust topics are you interested in?
@abdushakoor0099
@abdushakoor0099 2 ай бұрын
@@TrevorSullivan i don't know if this will be out of scope of the content you make but making a TUI with rust kinda stuff.
@TrevorSullivan
@TrevorSullivan 2 ай бұрын
@@abdushakoor0099 That's actually something that I want to do, yes! Thank you for the suggestion.
@abdushakoor0099
@abdushakoor0099 2 ай бұрын
@@TrevorSullivan amazing
@ThisGuyDakota
@ThisGuyDakota 9 ай бұрын
This is one of those topics I never understood in any language lol (this and recursive functions) I kind of understand how they're used, but no idea what a potential use-case would be so it's hard to practice
@TrevorSullivan
@TrevorSullivan 9 ай бұрын
After you spend a while learning the fundamentals, you can add in external libraries that allow you to build rich CLI apps, web APIs, games, and desktop applications. What are you interested in building?
@ThisGuyDakota
@ThisGuyDakota 9 ай бұрын
@TrevorSullivan currently don't have a project in mind, just want to learn rust for the sake of learning rust. I'm heavily into PowerShell, and I've dabbled with Python and C# a while ago. Just want to learn some low-level stuff to get a better understanding of what my PowerShell might be doing behind the scenes I guess. If I had to pick a project, I'd say maybe like a pong game or something. Although a CLI tool of some sort might be easier since I wouldn't have to learn gui stuff yet lol
@TrevorSullivan
@TrevorSullivan 9 ай бұрын
​@@ThisGuyDakota Nice, I come from a PowerShell background as well. It's awesome, but struggles performance-wise at scale. Knowing how to code in a lower-level language will help you build more efficient apps that scale faster and handle larger volumes of data. Rust (seems) to be the perfect balance of performance and developer friendliness. It's not "easy," but it also guides you along very nicely. 🦀 Rust on! 🦀 Thanks for joining me on the journey. Check out the "ratatui" crate, by the way, for building CLI apps. I'll get around to recording a video about it eventually.
@subhamprasad1373
@subhamprasad1373 8 ай бұрын
so lets say after calling change_name for the first time , then I want to execute so code that requires updated p1.last_name and I want call change_name , so am i not allowed to do that ??
@TrevorSullivan
@TrevorSullivan 8 ай бұрын
In that case, one option would be to derive the Clone trait on the object, so you can call .clone() on it. That way, you would have a separate object in memory that can be borrowed independently from the object you're trying to mutate. There might be more efficient solutions than that, but that's the easiest mechanism that I'm currently aware of.
@nhwhn
@nhwhn 3 ай бұрын
Liked and subscribed
@andyk2181
@andyk2181 3 ай бұрын
Can I suggest that you turn off your IDE's inline hints, or at least change the font and style. At the moment there is little to distinguish what you have typed as the code from what your editor is producing. For example, whether the colon in the closure parameters is explicitly typed, or inferred, is merely a matter of whether the color is purple or white. Anyone unfamiliar with how you have your particular IDE configured will not know what's what.
@TrevorSullivan
@TrevorSullivan 3 ай бұрын
Thanks for the feedback, Andy. I agree that the Rust Analyzer extension can make the inline type hints look like actual code. I need those type hints in order to write code effectively though. Maybe I can do a better job of calling out this fact in my videos.
@andyk2181
@andyk2181 3 ай бұрын
@@TrevorSullivan Looking at my own editor, I have the hints enabled, but they appear in gray so are more distinct from the code I've written. Perhaps you are using a high-contrast theme? Anyway, thanks for the video.
@SquirrltheRiddl
@SquirrltheRiddl 3 ай бұрын
is it just me who finds rust syntax sexy
@TrevorSullivan
@TrevorSullivan 3 ай бұрын
Haha you're definitely not the only one! It's different, but it has grown on me!
@teefus1
@teefus1 Ай бұрын
mee!
@user-eq7oo2cr1v
@user-eq7oo2cr1v Ай бұрын
Php is already too generic in its own genetic :) php interfaces easily sustains that intension. Other langs generialize their structure with generics.
Rust Match Expressions and Patterns 🦀
35:51
Trevor Sullivan
Рет қаралды 3,7 М.
Rust Functions and Modules 🦀
21:55
Trevor Sullivan
Рет қаралды 7 М.
OMG 😨 Era o tênis dela 🤬
00:19
Polar em português
Рет қаралды 11 МЛН
Pokey pokey 🤣🥰❤️ #demariki
00:26
Demariki
Рет қаралды 6 МЛН
Rust Functions Are Weird (But Be Glad)
19:52
Logan Smith
Рет қаралды 124 М.
rust macros are magic
14:02
Tantan
Рет қаралды 43 М.
Rust: Closures
19:53
The Dev Method
Рет қаралды 16 М.
Async Rust Is A Bad Language | Prime Reacts
28:46
ThePrimeTime
Рет қаралды 84 М.
Rust Powered Polymorphism ⚡️ With Traits
9:55
Code to the Moon
Рет қаралды 89 М.
Visualizing memory layout of Rust's data types
39:39
Sreekanth
Рет қаралды 8 М.
Rust Programming: The Ultimate Builder Pattern Tutorial
20:22
Jeremy Chone
Рет қаралды 37 М.
Smarter Programming in Rust: Master 'move' Now!
9:06
Flo Woelki
Рет қаралды 1,9 М.
Self-referential structs (in Rust)
27:21
fasterthanlime
Рет қаралды 51 М.
Use Arc Instead of Vec
15:21
Logan Smith
Рет қаралды 133 М.
МОЖНО ЛИ заряжать AirPods в чехле 🧐😱🧐 #airpods #applewatch #dyson
0:22
Apple_calls РЕПЛИКА №1 В РФ
Рет қаралды 20 М.
What percentage of charge is on your phone now? #entertainment
0:14
🤔Почему Samsung ПОМОГАЕТ Apple?
0:48
Technodeus
Рет қаралды 459 М.
⌨️ Сколько всего у меня клавиатур? #обзор
0:41
Гранатка — про VR и девайсы
Рет қаралды 653 М.
Цифровые песочные часы с AliExpress
0:45