A Tour of Go - Generics Flashcards

1
Q

What are generic functions in Go?

A

Go functions can be written to work on mulitple types using type parameters.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How is a generic function declared?

A

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 fulfils the built-in constraint comparable. x is also a value of the same type.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is the comparable constraint?

A

comparable is a useful constraint that makes it possible to use the == and != operators on values of the type.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Give an example of a generic function that compares a value to all slice elements until a match is found?

A
func Index[T comparable](s []T, x T) int {
	for i, v := range s {
		if v == x {
			return i
		}
	}
	return -1
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What are generic types in Go?

A

A type can be parameterised with a type parameter, which could be useful for implementing generic data structures.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Give an example of a generic list type?

A
type List[T any] struct {
	next *List[T]
	val  T
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly