Sobes.tech
Junior — Middle

Чем отличаются интерфейсы от обобщенных типов в программировании?

sobes.tech AI

Answer from AI

Interfaces and generics solve different problems in programming:

  • Interfaces describe a set of methods that a type must implement. They allow working with different types through a common contract, providing polymorphism. For example, the Reader interface in Go defines a Read() method, and any type implementing this method can be used as a Reader.

  • Generics enable writing functions and structures that work with different data types while maintaining type safety. They are templates parameterized by types, which are compiled for specific types when used.

Example in Go:

// Interface
 type Reader interface {
     Read(p []byte) (n int, err error)
 }

// Generic function
 func PrintSlice[T any](s []T) {
     for _, v := range s {
         fmt.Println(v)
     }
 }

Thus, interfaces define behavior, and generics provide code universality for different types.