Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Leer Introduction to Generics | Packages, Modules, and Generics
Practice
Projects
Quizzes & Challenges
Quizzen
Challenges
/
Advanced Go

bookIntroduction to Generics

Veeg om het menu te tonen

What Are Generics in Go?

Generics in Go let you write functions, types, and data structures that work with any data type. Instead of repeating similar code for different types, you define a single, flexible version using type parameters. This makes your code more reusable and easier to maintain.

Benefits of Using Generics

  • Code reusability: Share the same logic across multiple types without rewriting code;
  • Type safety: Catch type errors at compile time, reducing bugs;
  • Cleaner APIs: Simplify your interfaces by avoiding unnecessary conversions or empty interfaces (interface{});
  • Performance: Avoid runtime type assertions, which can slow down your code.

Generics in Go allow you to write functions and types that work with different data types without duplicating code. The syntax uses type parameters in square brackets [].

main.go

main.go

copy
12345678910111213141516
package main import "fmt" // A generic function that returns the first element of a slice func First[T any](slice []T) T { return slice[0] } func main() { nums := []int{1, 2, 3} words := []string{"hello", "world"} fmt.Println(First(nums)) // 1 fmt.Println(First(words)) // hello }
  • [T any]: T is a type parameter, and any means T can be any type;

  • First[T any](slice []T) T: the function takes a slice of any type T and returns an element of the same type;

  • Generics let you write reusable, type-safe code without repeating logic for different types.

Generics are especially useful when building data structures like stacks, queues, or maps, and when writing utility functions that operate on different types. By using generics, you write code that is both flexible and reliable.

question mark

Which statements about defining and using generics in Go are correct

Select all correct answers

Was alles duidelijk?

Hoe kunnen we het verbeteren?

Bedankt voor je feedback!

Sectie 2. Hoofdstuk 3

Vraag AI

expand

Vraag AI

ChatGPT

Vraag wat u wilt of probeer een van de voorgestelde vragen om onze chat te starten.

Sectie 2. Hoofdstuk 3
some-alt