تأكيدات النوع
تأكيدات النوع
يتيح تأكيد النوع الوصول إلى القيمة الفعلية الكامنة في قيمة الواجهة.
t := i.(T)
تؤكّد هذه التعليمة أن قيمة الواجهة i تحتوي على النوع الفعلي T
وتسند القيمة الكامنة من النوع T إلى المتغيّر t.
إذا لم تكن i تحتوي على قيمة من النوع T، فستؤدي التعليمة إلى حالة ذعر.
من أجل اختبار ما إذا كانت قيمة واجهة تحتوي على نوع محدّد، يمكن لتأكيد النوع إرجاع قيمتين: القيمة الكامنة وقيمة منطقية تبيّن ما إذا كان التأكيد قد نجح.
t, ok := i.(T)
إذا كانت i تحتوي على قيمة من النوع T، فستكون t القيمة الكامنة وستكون ok صائبة.
وإلا، فستكون ok خاطئة وستكون t القيمة الصفرية للنوع T،
ولن تحدث حالة ذعر.
لاحظ التشابه بين هذه الصيغة وصيغة القراءة من خريطة.
النص الأصلي بالإنجليزية
Type assertions
A type assertion provides access to an interface value's underlying concrete value.
t := i.(T)
This statement asserts that the interface value i holds the concrete type T
and assigns the underlying T value to the variable t.
If i does not hold a T, the statement will trigger a panic.
To test whether an interface value holds a specific type, a type assertion can return two values: the underlying value and a boolean value that reports whether the assertion succeeded.
t, ok := i.(T)
If i holds a T, then t will be the underlying value and ok will be true.
If not, ok will be false and t will be the zero value of type T,
and no panic occurs.
Note the similarity between this syntax and that of reading from a map.
هذا الدرس للقراءة فقط؛ جرّب المثال في الدرس التالي.