التكرار والإغلاق
التكرار والإغلاق
يمكن للمرسِل إغلاق قناة باستخدام close للإشارة إلى أنه لن تُرسل قيم أخرى. ويمكن للمستقبِلين التحقق مما إذا كانت القناة قد أُغلقت بإسناد معامل ثانٍ إلى تعبير الاستقبال: بعد
v, ok := <-ch
ok تكون قيمته false إذا لم تعد هناك قيم لاستقبالها وكانت القناة مغلقة.
تستقبل الحلقة for i := range c القيم من القناة مرارًا حتى تُغلق.
ملاحظة: ينبغي أن يغلق القناة المرسِل وحده، لا المستقبِل أبدًا. سيؤدي الإرسال إلى قناة مغلقة إلى حالة هلع.
ملاحظة أخرى: القنوات ليست كالملفات؛ لا تحتاج عادةً إلى إغلاقها. لا يكون الإغلاق ضروريًا إلا حين يجب إبلاغ المستقبِل بأنه لن تصل قيم أخرى، مثل إنهاء حلقة range.
النص الأصلي بالإنجليزية
Range and Close
A sender can close a channel to indicate that no more values will be sent. Receivers can test whether a channel has been closed by assigning a second parameter to the receive expression: after
v, ok := <-ch
ok is false if there are no more values to receive and the channel is closed.
The loop for i := range c receives values from the channel repeatedly until it is closed.
Note: Only the sender should close a channel, never the receiver. Sending on a closed channel will cause a panic.
Another note: Channels aren't like files; you don't usually need to close them. Closing is only necessary when the receiver must be told there are no more values coming, such as to terminate a range loop.
هذا الدرس للقراءة فقط؛ جرّب المثال في الدرس التالي.