معاملات الأنواع
معاملات الأنواع
يمكن كتابة دوال Go لتعمل على أنواع متعددة باستخدام معاملات الأنواع. وتظهر معاملات الأنواع الخاصة بالدالة بين قوسين مربعين، قبل وسائط الدالة.
func Index[T comparable](s []T, x T) int
يعني هذا التصريح أن s شريحة من أي نوع T يستوفي
القيد المضمّن comparable. وx أيضًا قيمة من النوع نفسه.
comparable قيد مفيد يتيح استخدام العاملين == و
!= على قيم النوع. في هذا المثال، نستخدمه لمقارنة
قيمة بجميع عناصر الشريحة حتى نجد تطابقًا. تعمل دالة Index هذه
مع أي نوع يدعم المقارنة.
النص الأصلي بالإنجليزية
Type parameters
Go functions can be written to work on multiple types using type parameters. The type parameters of a function appear between brackets, before the function's arguments.
func Index[T comparable](s []T, x T) int
This declaration means that s is a slice of any type T that fulfills the
built-in constraint comparable. x is also a value of the same type.
comparable is a useful constraint that makes it possible to use the == and
!= operators on values of the type. In this example, we use it to compare a
value to all slice elements until a match is found. This Index function works
for any type that supports comparison.
هذا الدرس للقراءة فقط؛ جرّب المثال في الدرس التالي.