docs(10_Wiki): Topic_Business/General/Graphic/Programming을 Topics/ 하위로 이동
최상위 10_Wiki/Topic_*였던 4개 카테고리 폴더를 10_Wiki/Topics/Topic_* 로 재배치. 콘텐츠 변경 없음(순수 폴더 이동) — Topics/ 하위 나머지 폴더는 이미 지난 커밋에서 전부 정리된 상태(잔존 항목은 에이전트 운영 상태 및 사용자가 보존을 요청한 업데이트0615/무제 3.canvas 뿐).
This commit is contained in:
@@ -0,0 +1,146 @@
|
||||
---
|
||||
id: wiki-2026-0508-generics-and-polymorphism
|
||||
title: Generics and Polymorphism
|
||||
category: 10_Wiki/Topics
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [Parametric Polymorphism, 제네릭]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.9
|
||||
verification_status: applied
|
||||
tags: [type-system, generics, polymorphism]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
tech_stack:
|
||||
language: typescript
|
||||
framework: type-system
|
||||
---
|
||||
|
||||
# Generics and Polymorphism
|
||||
|
||||
## 매 한 줄
|
||||
> **"매 한 번 작성, 매 여러 type 에 작동"**. 매 parametric polymorphism (generics) + ad-hoc polymorphism (overloading / traits) + subtype polymorphism (inheritance) 의 셋이 modern type system 의 backbone. 2026 시점 TS 5.x conditional types, Rust trait + GAT, Go 1.21+ generics 가 매 mainstream.
|
||||
|
||||
## 매 핵심
|
||||
|
||||
### 매 polymorphism 의 종류
|
||||
- **Parametric**: type parameter `<T>` — 매 List<T>, Vec<T>, []T.
|
||||
- **Ad-hoc**: overloading, type classes, traits, interfaces with default impl.
|
||||
- **Subtype**: 매 Liskov — Cat extends Animal.
|
||||
- **Row / Structural**: TS object shape, OCaml row polymorphism.
|
||||
|
||||
### 매 dispatch
|
||||
- **Static (monomorphization)**: Rust, C++ template — 매 compile-time 에 specialize → zero overhead.
|
||||
- **Dynamic (vtable)**: Java interface, Go interface, Rust dyn Trait — 매 runtime indirection.
|
||||
|
||||
### 매 응용
|
||||
1. Collection / container 의 reuse.
|
||||
2. Algorithm 의 generic write (sort, map).
|
||||
3. API design 의 type-safe abstraction.
|
||||
4. Dependency injection 의 decoupling.
|
||||
|
||||
## 💻 패턴
|
||||
|
||||
### TypeScript — generic constraint
|
||||
```ts
|
||||
function pluck<T, K extends keyof T>(items: T[], key: K): T[K][] {
|
||||
return items.map(i => i[key]);
|
||||
}
|
||||
const names = pluck([{ id: 1, name: "Ada" }], "name"); // string[]
|
||||
```
|
||||
|
||||
### TS — conditional + infer
|
||||
```ts
|
||||
type ReturnT<F> = F extends (...a: any[]) => infer R ? R : never;
|
||||
type X = ReturnT<() => Promise<number>>; // Promise<number>
|
||||
```
|
||||
|
||||
### Rust — trait + generic
|
||||
```rust
|
||||
trait Summable: Copy + std::ops::Add<Output = Self> + Default {}
|
||||
impl<T: Copy + std::ops::Add<Output = T> + Default> Summable for T {}
|
||||
|
||||
fn sum<T: Summable>(xs: &[T]) -> T {
|
||||
xs.iter().copied().fold(T::default(), |a, b| a + b)
|
||||
}
|
||||
```
|
||||
|
||||
### Rust — GAT (Generic Associated Type)
|
||||
```rust
|
||||
trait LendingIterator {
|
||||
type Item<'a> where Self: 'a;
|
||||
fn next<'a>(&'a mut self) -> Option<Self::Item<'a>>;
|
||||
}
|
||||
```
|
||||
|
||||
### Rust — dyn vs impl Trait
|
||||
```rust
|
||||
fn make_static() -> impl Iterator<Item = i32> { (0..10).filter(|x| x % 2 == 0) } // monomorphized
|
||||
fn make_dyn() -> Box<dyn Iterator<Item = i32>> { Box::new(0..10) } // vtable
|
||||
```
|
||||
|
||||
### Go — generics (1.21+)
|
||||
```go
|
||||
type Number interface { ~int | ~int64 | ~float64 }
|
||||
|
||||
func Sum[T Number](xs []T) T {
|
||||
var total T
|
||||
for _, x := range xs { total += x }
|
||||
return total
|
||||
}
|
||||
```
|
||||
|
||||
### Java — bounded wildcard (PECS)
|
||||
```java
|
||||
// Producer Extends, Consumer Super
|
||||
static double sum(List<? extends Number> xs) {
|
||||
double s = 0; for (Number n : xs) s += n.doubleValue(); return s;
|
||||
}
|
||||
static void fillWithOnes(List<? super Integer> xs) { xs.add(1); }
|
||||
```
|
||||
|
||||
### Haskell — type class (ad-hoc)
|
||||
```haskell
|
||||
class Eq a where
|
||||
(==) :: a -> a -> Bool
|
||||
instance Eq Int where x == y = primEqInt x y
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| Container reuse | parametric `<T>` |
|
||||
| Multiple impl 의 한 interface | trait / interface |
|
||||
| Hot path, type set 작음 | monomorphization (Rust, C++ template) |
|
||||
| Heterogeneous collection | dyn Trait / interface{} / Box<dyn> |
|
||||
| Known finite variants | sum type (enum / discriminated union) — 매 generic 보다 simple |
|
||||
|
||||
**기본값**: TS / Java 는 generics + interface, Rust 는 generic + trait (static dispatch).
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[TypeScript 타입 시스템 (TypeScript Type System)|Type Systems]] · [[Polymorphism]]
|
||||
- 변형: [[Subtype Polymorphism]]
|
||||
- Adjacent: [[Variance]] · [[Sum Types]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: API surface design / type signature 의 reasoning / variance bug 진단.
|
||||
**언제 X**: 매 simple concrete type 만 쓰는 곳에 generic 강제 — 매 over-abstraction.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Generic for one caller**: 매 YAGNI — 매 concrete 부터.
|
||||
- **Unbounded `<T>` 의 남용**: 매 actually 필요한 constraint 누락.
|
||||
- **Variance 무시 (Java)**: `List<Cat>` 을 `List<Animal>` 자리에 — covariance bug.
|
||||
- **dyn Trait everywhere (Rust)**: 매 hot path 에서 vtable cost 누적.
|
||||
- **Type erasure 의 망각 (Java)**: runtime 에 `T` 의 reflection 시도.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Pierce *TAPL* 2002, Rust Reference, TS Handbook 5.x, Go spec 1.21).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — TS/Rust/Go/Java generics + polymorphism 종류 정리 |
|
||||
Reference in New Issue
Block a user