filmov
tv
Advanced Golang: Channels, Context and Interfaces Explained
![preview_player](https://i.ytimg.com/vi/VkGQFFl66X4/maxresdefault.jpg)
Показать описание
Today, I'll provide a simple breakdown of channels, context and interfaces in Golang. I'll show examples of why they are useful and how to properly use them in the real world.
0:00 Intro
0:17 Channels
8:35 Context
13:55 Interfaces
21:53 Conclusion
Channels are a safe way of transferring data between goroutines without using a mutex. You can send data to a channel in one goroutine, then consume data from the same channel in another goroutine. By default, a channel does not have space to store data, so you must simultaneously send and receive data from the channel to avoid a deadlock. A buffered channel allows you to allocate space to temporarily store data in the channel.
Context is an object that can be safely passed to multiple goroutines to provide a way to implement a timeout or cancellation to a function. 3rd party libraries that make HTTP requests or database requests typically have support for providing your own context so you cancel those operations.
Interfaces are a great way to enforce a blueprint for what your app can do, similar to object oriented programming. For example, there are many different types of bank accounts, but you can use a single interface to interact with all of them: GetBalance(), Deposit() and Withdraw(). This makes your high-level code easier to work with because the implementation is abstracted away.
0:00 Intro
0:17 Channels
8:35 Context
13:55 Interfaces
21:53 Conclusion
Channels are a safe way of transferring data between goroutines without using a mutex. You can send data to a channel in one goroutine, then consume data from the same channel in another goroutine. By default, a channel does not have space to store data, so you must simultaneously send and receive data from the channel to avoid a deadlock. A buffered channel allows you to allocate space to temporarily store data in the channel.
Context is an object that can be safely passed to multiple goroutines to provide a way to implement a timeout or cancellation to a function. 3rd party libraries that make HTTP requests or database requests typically have support for providing your own context so you cancel those operations.
Interfaces are a great way to enforce a blueprint for what your app can do, similar to object oriented programming. For example, there are many different types of bank accounts, but you can use a single interface to interact with all of them: GetBalance(), Deposit() and Withdraw(). This makes your high-level code easier to work with because the implementation is abstracted away.
Комментарии