Text file tour/generics.article

     1  Generics
     2  Go supports generic programming using type parameters. This lesson shows some examples for employing generics in your code.
     3  
     4  The Go Authors
     5  https://golang.org
     6  
     7  * Type parameters
     8  
     9  Go functions can be written to work on multiple types using type parameters. The
    10  type parameters of a function appear between brackets, before the function's
    11  arguments.
    12  
    13    func Index[T comparable](s []T, x T) int
    14  
    15  This declaration means that `s` is a slice of any type `T` that fulfills the
    16  built-in constraint `comparable`. `x` is also a value of the same type.
    17  
    18  `comparable` is a useful constraint that makes it possible to use the `==` and
    19  `!=` operators on values of the type. In this example, we use it to compare a
    20  value to all slice elements until a match is found. This `Index` function works
    21  for any type that supports comparison.
    22  
    23  .play generics/index.go
    24  
    25  * Generic types
    26  
    27  In addition to generic functions, Go also supports generic types. A type can
    28  be parameterized with a type parameter, which could be useful for implementing
    29  generic data structures.
    30  
    31  This example demonstrates a simple type declaration for a singly-linked list
    32  holding any type of value.
    33  
    34  As an exercise, add some functionality to this list implementation.
    35  
    36  .play generics/list.go
    37  
    38  * Congratulations!
    39  
    40  You finished this lesson!
    41  
    42  You can go back to the list of [[/tour/list][modules]] to find what to learn next, or continue with the [[javascript:click('.next-page')][next lesson]].
    43  

View as plain text