Go

Generics

Type parameters, constraints, comparable, any, generic functions, generic types, type inference

20 mülakat soruları·
Senior
1

What is a type parameter in Go?

Cevap

A type parameter is a type variable used in generic function or type definitions, declared within square brackets. It enables writing reusable code that works with different types without sacrificing type safety. Type parameters are instantiated with concrete type arguments when used, allowing the compiler to verify type consistency at compile time rather than runtime.

2

What is the correct syntax to declare a simple generic function?

Cevap

The correct syntax for declaring a generic function uses square brackets immediately after the function name to define type parameters. The any constraint allows accepting any type, similar to interface{} but with clearer semantics in the context of generics. This syntax was introduced in Go 1.18 to enable generic programming while maintaining language simplicity.

3

What does the 'any' constraint represent in Go?

Cevap

The any constraint is an alias for interface{} that represents the set of all possible types in Go. It allows a type parameter to accept any type without restriction, offering maximum flexibility. While convenient, using any means giving up specific type checking and often requires type assertions to access methods or properties of the underlying type.

4

What is the main difference between 'any' and 'comparable' as constraints?

5

How to declare a custom generic type like a stack?

+17 mülakat soruları

Bir sonraki mülakatın için Go'de uzmanlaş

Tüm sorulara, flashcards'a, teknik testlere, code review alıştırmalarına ve mülakat simülatörlerine eriş.

Ücretsiz başla