Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lära Introduction to Generics | Packages, Modules, and Generics
Advanced Go

bookIntroduction to Generics

Svep för att visa menyn

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

Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 2. Kapitel 3

Fråga AI

expand

Fråga AI

ChatGPT

Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal

Avsnitt 2. Kapitel 3
some-alt