Rust 에서 trait 를 구현한 타입을 인자로 받는 방법은 두 가지다. 제네릭 T: Shape(또는 impl Shape)로 받으면 컴파일러가 호출된 타입마다 함수 사본을 만든다. &dyn Shape 로 받으면 함수는 하나만 생기고, 실행 중에 vtable 에서 구현 주소를 읽어 호출한다. 고르는 기준은 여러 타입을 한 곳에 섞어야 하는지, 사본이 늘어나는 비용과 간접 호출 비용 중 어느 쪽이 문제인지에 달려 있다고 봤다.
두 방식의 차이를 문서 설명이 아니라 컴파일 결과로 확인하고 싶었다. 그래서 제네릭 함수의 심벌은 nm 으로, dyn 호출과 vtable 은 rustc 가 출력한 어셈블리로 봤다. 아래 예제는 모두 rustc 1.94.1, edition 2021 에서 컴파일했고, 심벌과 어셈블리는 aarch64-apple-darwin(Apple Silicon macOS)에서 추출했다.
trait 정의와 기본 메서드
trait 는 타입이 구현해야 할 메서드 시그니처의 묶음이다. 본문을 함께 적은 메서드는 기본 메서드가 되고, 구현하는 타입이 다시 정의하지 않으면 그 본문을 쓴다.
trait Shape {
fn area(&self) -> f64;
fn describe(&self) -> String {
format!("area {:.1}", self.area())
}
}
struct Circle {
radius: f64,
}
struct Rect {
width: f64,
height: f64,
}
impl Shape for Circle {
fn area(&self) -> f64 {
3.14 * self.radius * self.radius
}
}
impl Shape for Rect {
fn area(&self) -> f64 {
self.width * self.height
}
fn describe(&self) -> String {
format!("{}x{} rect", self.width, self.height)
}
}
fn main() {
let circle = Circle { radius: 1.0 };
let rect = Rect { width: 2.0, height: 3.0 };
println!("{}", circle.describe());
println!("{}", rect.describe());
}
area 3.1
2x3 rect
Circle 은 area 만 구현했으므로 기본 describe 가 쓰이고, Rect 는 describe 를 다시 정의했다. 이 글의 나머지 예제는 이 Shape, Circle, Rect 를 그대로 쓴다.
trait bound 와 where 절
제네릭 함수 안에서 타입 매개변수 T 의 메서드를 부르려면, T 가 그 메서드가 있는 trait 를 구현한다고 적어야 한다. 이 조건이 trait bound 다. bound 없이 area 를 부르면 컴파일되지 않는다.
trait Shape {
fn area(&self) -> f64;
}
fn total_area<T>(shapes: &[T]) -> f64 {
shapes.iter().map(|s| s.area()).sum()
}
fn main() {}
error[E0599]: no method named `area` found for reference `&T` in the current scope
--> bound_err.rs:6:29
|
6 | shapes.iter().map(|s| s.area()).sum()
| ^^^^ method not found in `&T`
|
= help: items from traits can only be used if the type parameter is bounded by the trait
help: the following trait defines an item `area`, perhaps you need to restrict type parameter `T` with it:
|
5 | fn total_area<T: Shape>(shapes: &[T]) -> f64 {
| +++++++
컴파일러가 본문에서 T 로 아는 것은 bound 뿐이다. T 가 어떤 타입으로 채워질지 모르는 상태로 본문을 검사하므로, bound 에 없는 메서드는 호출할 수 없다. 제안대로 T: Shape 를 붙이면 컴파일된다.
bound 가 여러 개면 꺾쇠 안이 길어진다. 이때는 시그니처 뒤에 where 절로 옮겨 적을 수 있다. 이 예제에서는 꺾쇠 안에 적은 것과 의미가 같다.
use std::fmt::Debug;
// Shape 는 위와 같다
#[derive(Debug)]
struct Circle {
radius: f64,
}
// impl Shape for Circle 은 위와 같다
fn print_largest<T>(shapes: &[T])
where
T: Shape + Debug,
{
if let Some(largest) = shapes.iter().max_by(|a, b| a.area().total_cmp(&b.area())) {
println!("{largest:?}");
}
}
fn main() {
let circles = [Circle { radius: 1.0 }, Circle { radius: 3.0 }];
print_largest(&circles);
}
Circle { radius: 3.0 }
monomorphization — 타입마다 함수 사본
제네릭 함수는 컴파일 결과에 하나로 남지 않는다. 컴파일러는 호출된 구체 타입마다 T 를 그 타입으로 바꾼 사본을 만든다. 이 과정이 monomorphization 이다. 그림 위쪽이 제네릭, 아래쪽이 다음 절에서 볼 dyn 이다.
print_area 를 Circle 과 Rect 로 한 번씩 부르는 프로그램을 컴파일해 심벌을 확인했다. 최적화(-O)에서 함수가 호출한 쪽에 인라인되어 사라지지 않도록 #[inline(never)] 를 붙였다.
// Shape, Circle, Rect 는 위와 같다
#[inline(never)]
fn print_area<T: Shape>(shape: &T) {
println!("{:.1}", shape.area());
}
fn main() {
print_area(&Circle { radius: 1.0 });
print_area(&Rect { width: 2.0, height: 3.0 });
}
$ rustc --edition 2021 -O -C symbol-mangling-version=v0 mono.rs
$ nm -C mono | grep print_area
0000000100001ac0 t mono::print_area::<mono::Rect>
0000000100001b00 t mono::print_area::<mono::Circle>
소스의 print_area 하나가 바이너리에서는 print_area::<Rect> 와 print_area::<Circle> 두 함수가 됐다. -C symbol-mangling-version=v0 는 심벌 이름에 제네릭 인자를 남기는 v0 맹글링을 고르는 옵션이다. 기본 맹글링에서는 두 심벌이 mono::print_area::h… 처럼 해시만 다르게 나온다.
각 사본 안에서 shape.area() 는 어느 구현을 부를지 컴파일할 때 정해진다. Rust Book 은 이를 정적 디스패치(static dispatch)라고 부른다. 함수를 부르는 구체 타입이 늘어날수록 같은 본문이 그만큼 더 컴파일되고 바이너리에 들어간다.
dyn Trait 와 vtable
같은 함수를 &dyn Shape 로 받게 바꾸고 다시 심벌을 봤다.
// Shape, Circle, Rect 는 위와 같다
#[inline(never)]
fn print_area(shape: &dyn Shape) {
println!("{:.1}", shape.area());
}
fn main() {
print_area(&Circle { radius: 1.0 });
print_area(&Rect { width: 2.0, height: 3.0 });
println!("&Circle = {} bytes", std::mem::size_of::<&Circle>());
println!("&dyn Shape = {} bytes", std::mem::size_of::<&dyn Shape>());
}
3.1
6.0
&Circle = 8 bytes
&dyn Shape = 16 bytes
$ nm -C dyn_mono | grep area
0000000100001a74 t dyn_mono::print_area
0000000100001b3c t <dyn_mono::Circle as dyn_mono::Shape>::area
0000000100001b60 t <dyn_mono::Rect as dyn_mono::Shape>::area
이번에는 print_area 가 하나만 있다. 대신 &dyn Shape 의 크기가 &Circle 의 두 배인 16바이트다.
&dyn Shape 는 포인터 두 개로 된 fat pointer 다. 하나는 값(Circle)을 가리키고, 다른 하나는 그 타입의 vtable 을 가리킨다. The Rust Reference 는 vtable 을 구체 타입이 구현한 trait 메서드마다 함수 포인터를 하나씩 담은 표로 설명한다. 참조와 borrow 글에서 본 &str 이 포인터와 길이를 함께 포함하는 것처럼, 두 번째 포인터 자리에 길이 대신 vtable 주소가 들어간다.
rustc 는 vtable 을 상수로 출력한다. 정적 변수를 &dyn Shape 로 돌려주는 함수를 라이브러리로 컴파일해 어셈블리를 확인했다.
pub trait Shape {
fn area(&self) -> f64;
fn describe(&self) -> String {
format!("area {:.1}", self.area())
}
}
pub struct Circle {
pub radius: f64,
}
impl Shape for Circle {
fn area(&self) -> f64 {
3.14 * self.radius * self.radius
}
}
pub static UNIT: Circle = Circle { radius: 1.0 };
#[inline(never)]
pub fn unit_shape() -> &'static dyn Shape {
&UNIT
}
$ rustc --edition 2021 -O --crate-type=lib -C symbol-mangling-version=v0 --emit=asm vtable2.rs
$ grep -A3 '^l_anon.*\.0:' vtable2.s
l_anon.60c15bf517e2d5c696fd7e336c057abe.0:
.asciz "\000\000\000\000\000\000\000\000\b\000\000\000\000\000\000\000\b\000\000\000\000\000\000"
.quad __RNvXCs1umv6GY0ZL6_7vtable2NtB2_6CircleNtB2_5Shape4area
.quad __RNvYNtCs1umv6GY0ZL6_7vtable26CircleNtB4_5Shape8describeB4_
.asciz 줄은 끝의 0 바이트까지 24바이트로, 8바이트 칸 세 개다. 첫 칸은 0, 둘째와 셋째 칸은 8(\b)이다. 그 뒤 두 .quad 는 nm -C 로 풀면 <Circle as Shape>::area 와 <Circle as Shape>::describe 다. 기본 메서드 describe 도 Circle 용 사본이 만들어져 vtable 에 들어갔다.
앞 세 칸은 DynMetadata 문서가 vtable 에 들어 있다고 적은 drop 함수 포인터, 크기, 정렬이다. Circle 은 f64 하나라 크기와 정렬이 8 이다. drop 칸이 0 인 것은 Circle 에 drop 할 것이 없어 함수 주소를 넣지 않은 것으로 봤다. 이 칸 순서는 언어가 보장하는 형식이 아니고, rustc 1.94.1 이 만든 결과를 본 것이다.
호출 경로 비교
vtable 이 호출 비용에 어떻게 나타나는지 보려고, &Circle 로 받는 함수와 &dyn Shape 로 받는 함수를 나란히 컴파일했다.
pub trait Shape {
fn area(&self) -> f64;
}
pub struct Circle {
pub radius: f64,
}
impl Shape for Circle {
fn area(&self) -> f64 {
3.14 * self.radius * self.radius
}
}
#[inline(never)]
pub fn area_static(shape: &Circle) -> f64 {
shape.area()
}
#[inline(never)]
pub fn area_dyn(shape: &dyn Shape) -> f64 {
shape.area()
}
--emit=asm 출력에서 .cfi 같은 어셈블러 지시어와 레이블을 걸러낸 결과다.
__RNvCsYsckr2IOkS_8dispatch11area_static:
ldr d0, [x0]
mov x8, #34079
movk x8, #20971, lsl #16
movk x8, #7864, lsl #32
movk x8, #16393, lsl #48
fmov d1, x8
fmul d1, d0, d1
fmul d0, d0, d1
ret
__RNvCsYsckr2IOkS_8dispatch8area_dyn:
ldr x1, [x1, #24]
br x1
area_static 에는 Circle::area 호출이 남아 있지 않다. 컴파일러가 본문을 인라인해 radius 를 읽고, 3.14 상수를 만들고, 곱셈 두 번을 수행한다. 제네릭 print_area::<Circle> 안의 shape.area() 도 구현이 컴파일할 때 정해지므로 같은 방식으로 인라인할 수 있다. area_dyn 은 인자로 받은 두 포인터 중 vtable 쪽(x1)에서 24바이트 떨어진 칸을 읽고 그 주소로 분기한다. 24 는 앞 절의 drop·크기·정렬 세 칸 뒤, 첫 메서드 area 의 위치다.
area_dyn 자체는 두 줄이지만, 분기한 곳에서 Circle::area 본문이 따로 실행된다. 호출할 함수가 실행 중에 정해지므로 area_dyn 안에서는 area 본문을 인라인할 수 없다. Rust Book 도 동적 디스패치가 인라인을 막아 일부 최적화를 할 수 없게 한다고 설명한다. 이 예제는 #[inline(never)] 로 함수 경계를 고정했고, 호출하는 쪽에서 구체 타입이 보이면 최적화기가 간접 호출을 없앨 수도 있다. 반복문 안에서 작은 메서드를 dyn 으로 부르는 코드라면 이 차이가 누적된다고 봤다. 실행 시간은 측정하지 않았다.
여러 타입을 한 컬렉션에 담기
Vec<T> 의 원소 타입 T 는 하나다. 그래서 Circle 과 Rect 를 한 Vec 에 넣으면 vec! 에서 바로 E0308 이 난다.
// Shape, Circle, Rect 는 위와 같다
fn total_area<T: Shape>(shapes: &[T]) -> f64 {
shapes.iter().map(|s| s.area()).sum()
}
fn main() {
let shapes = vec![Circle { radius: 1.0 }, Rect { width: 2.0, height: 3.0 }];
println!("{}", total_area(&shapes));
}
error[E0308]: mismatched types
--> hetero_err.rs:31:47
|
31 | let shapes = vec![Circle { radius: 1.0 }, Rect { width: 2.0, height: 3.0 }];
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `Circle`, found `Rect`
원소 타입을 Box<dyn Shape> 하나로 정하면 컴파일된다. 값은 각자 힙에 놓이고, Vec 에는 어떤 타입을 가리키든 16바이트인 포인터 쌍이 들어간다.
// Shape, Circle, Rect 는 위와 같다
fn total_area(shapes: &[Box<dyn Shape>]) -> f64 {
shapes.iter().map(|s| s.area()).sum()
}
fn main() {
let shapes: Vec<Box<dyn Shape>> = vec![
Box::new(Circle { radius: 1.0 }),
Box::new(Rect { width: 2.0, height: 3.0 }),
];
println!("{:.2}", total_area(&shapes));
println!("Box<dyn Shape> = {} bytes", std::mem::size_of::<Box<dyn Shape>>());
}
9.14
Box<dyn Shape> = 16 bytes
원소마다 자기 타입의 vtable 주소를 포함하므로, total_area 는 원소가 어떤 타입인지 몰라도 각자의 area 를 부른다. Box 의 힙 할당은 이 글에서 다루지 않는다.
impl Trait — 인자 위치와 반환 위치
인자 위치의 fn print_area(shape: &impl Shape) 는 The Rust Reference 가 <T: Shape> 의 문법 설탕이라고 적은 형태다. monomorphization 도 똑같이 일어난다. 차이는 타입 매개변수에 이름이 없다는 점이다. 그래서 호출하는 쪽이 print_area::<Circle>(…) 처럼 타입을 직접 지정할 수 없다.
반환 위치의 -> impl Shape 는 “이 함수는 Shape 를 구현한 어떤 타입 하나를 돌려준다"는 뜻이다. 그 타입은 함수가 정하고, 호출하는 쪽은 구체 타입 이름을 모른 채 Shape 메서드만 쓴다. 다만 타입은 하나여야 한다. 입력에 따라 다른 타입을 돌려주면 거부된다.
// Shape, Circle, Rect 는 위와 같다
fn parse_shape(spec: &str) -> impl Shape {
if spec == "circle" {
Circle { radius: 1.0 }
} else {
Rect { width: 2.0, height: 3.0 }
}
}
fn main() {
println!("{}", parse_shape("circle").area());
}
error[E0308]: `if` and `else` have incompatible types
--> impl_ret_err.rs:30:9
|
27 | / if spec == "circle" {
28 | | Circle { radius: 1.0 }
| | ---------------------- expected because of this
29 | | } else {
30 | | Rect { width: 2.0, height: 3.0 }
| | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `Circle`, found `Rect`
31 | | }
| |_____- `if` and `else` have incompatible types
|
help: you could change the return type to be a boxed trait object
|
26 - fn parse_shape(spec: &str) -> impl Shape {
26 + fn parse_shape(spec: &str) -> Box<dyn Shape> {
|
help: if you change the return type to expect trait objects, box the returned expressions
|
28 ~ Box::new(Circle { radius: 1.0 })
29 | } else {
30 ~ Box::new(Rect { width: 2.0, height: 3.0 })
|
impl Shape 는 컴파일할 때 정해지는 구체 타입 하나를 숨긴 것이다. 사본이 생기지 않는 대신, 실행 중 값에 따라 타입이 달라지는 경우를 표현하지 못한다. 컴파일러도 Box<dyn Shape> 로 바꾸라고 제안한다. 반환 타입이 하나로 정해지는 함수는 그대로 impl Shape 를 쓰면 된다.
// Shape, Circle, Rect 는 위와 같다
fn parse_shape(spec: &str) -> Box<dyn Shape> {
if spec == "circle" {
Box::new(Circle { radius: 1.0 })
} else {
Box::new(Rect { width: 2.0, height: 3.0 })
}
}
fn unit_circle() -> impl Shape {
Circle { radius: 1.0 }
}
fn main() {
println!("{:.2}", parse_shape("circle").area());
println!("{:.2}", parse_shape("rect").area());
println!("{:.2}", unit_circle().area());
}
3.14
6.00
3.14
dyn compatibility — vtable 을 만들 수 있는 trait
모든 trait 를 dyn 으로 쓸 수 있지는 않다. vtable 은 구체 타입마다 메서드 주소를 한 칸씩 담는 표인데, 칸을 만들 수 없는 메서드가 where Self: Sized 로 빠져 있지 않으면 그 trait 는 dyn 으로 쓸 수 없다. 이 글은 메서드에서 흔한 두 경우만 다루고, 전체 조건은 Reference 의 dyn compatibility 절에 있다. 이 조건을 예전에는 object safety 라고 불렀고, Rust 1.83 에 들어간 컴파일러 변경부터 dyn compatibility 로 이름이 바뀌었다.
Self 를 반환하는 메서드를 추가하면 &dyn Shape 를 쓰는 코드가 컴파일되지 않는다.
trait Shape {
fn area(&self) -> f64;
fn scaled(&self, factor: f64) -> Self;
}
fn print_area(shape: &dyn Shape) {
println!("{}", shape.area());
}
fn main() {}
error[E0038]: the trait `Shape` is not dyn compatible
--> dyn_compat_err.rs:6:23
|
6 | fn print_area(shape: &dyn Shape) {
| ^^^^^^^^^ `Shape` is not dyn compatible
|
note: for a trait to be dyn compatible it needs to allow building a vtable
for more information, visit <https://doc.rust-lang.org/reference/items/traits.html#dyn-compatibility>
--> dyn_compat_err.rs:3:38
|
1 | trait Shape {
| ----- this trait is not dyn compatible...
2 | fn area(&self) -> f64;
3 | fn scaled(&self, factor: f64) -> Self;
| ^^^^ ...because method `scaled` references the `Self` type in its return type
= help: consider moving `scaled` to another trait
dyn Shape 뒤의 구체 타입은 실행 중에만 알 수 있다. scaled 를 dyn 으로 부르면 반환값이 Circle 인지 Rect 인지, 몇 바이트를 받아야 하는지 호출하는 쪽이 컴파일할 때 알 수 없다. 메서드에 타입 매개변수를 두어도 같은 E0038 이 난다. fn scale_by<F: Into<f64>>(&self, factor: F) 로 바꾸면 이유가 ...because method `scale_by` has generic type parameters 로 나온다. F 마다 사본이 필요한데 vtable 에는 칸을 미리 정해 둬야 하기 때문이다.
메서드에 where Self: Sized 를 붙이면 그 메서드만 vtable 에서 빠지고, trait 는 다시 dyn 으로 쓸 수 있다.
trait Shape {
fn area(&self) -> f64;
fn scaled(&self, factor: f64) -> Self
where
Self: Sized;
}
// Circle 과 impl Shape for Circle (scaled 포함) 은 생략
fn print_area(shape: &dyn Shape) {
println!("{:.2}", shape.area());
}
fn main() {
let circle = Circle { radius: 1.0 };
let bigger = circle.scaled(2.0);
print_area(&circle);
print_area(&bigger);
}
3.14
12.56
scaled 는 circle 처럼 구체 타입을 아는 자리에서만 부를 수 있다. &dyn Shape 에서 shape.scaled(2.0) 을 부르면 the `scaled` method cannot be invoked on a trait object 에러가 난다. 이 trait 의 vtable 을 앞 절과 같은 방법으로 추출하면 drop·크기·정렬 세 칸 뒤에 area 한 칸만 있다.
$ grep -A2 '^l_anon.*\.0:' vtable_sized.s
l_anon.9b7a0b330995a7234a55b9e0bc8ba3fc.0:
.asciz "\000\000\000\000\000\000\000\000\b\000\000\000\000\000\000\000\b\000\000\000\000\000\000"
.quad __RNvXCsfxFx7uliNFX_12vtable_sizedNtB2_6CircleNtB2_5Shape4area
선택 기준
기본값은 제네릭이나 impl Trait 로 두는 쪽이 맞다고 봤다. 호출할 구현이 컴파일할 때 정해지고, 인라인도 가능하다. dyn 이 필요한지는 그림의 세 질문으로 판단했다.
- 여러 타입을 섞어야 할 때. 한
Vec·HashMap·struct 필드에 서로 다른 구체 타입을 담는 경우다. 타입 목록이 미리 정해져 있으면 enum 으로 묶을 수도 있지만, 플러그인이나 이벤트 핸들러처럼 목록이 열려 있으면dyn이 필요하다. - 반환 타입이 실행 중에 정해질 때. 설정값이나 입력에 따라 다른 타입을 돌려주는 함수는
impl Trait로 표현할 수 없다. 돌려줄 타입이 정해진 몇 개라면 enum 으로 묶을 수 있고, 그렇지 않으면Box<dyn Trait>를 돌려준다. - 사본이 부담일 때. 크고 자주 쓰이는 제네릭 함수를 수많은 타입으로 부르면 같은 본문이 타입 수만큼 컴파일되어 빌드 시간과 바이너리 크기가 늘어난다. 이 글에서 그 크기를 측정하지는 않았다. 그쪽이 문제라면
dyn으로 사본을 하나로 줄이거나, 제네릭 함수는 인자 변환만 하고 본문은 타입과 무관한 일반 함수에 맡기는 방법을 검토한다. 반대로 반복문 안에서 자주 부르는 작은 메서드라면 인라인할 수 있는 제네릭을 유지한다.
어느 쪽이든 dyn 을 고르면 trait 가 dyn compatible 해야 한다. Self 를 반환하거나 타입 매개변수를 받는 메서드는 where Self: Sized 로 vtable 에서 빼거나 별도 trait 로 옮긴다.
마무리
제네릭은 컴파일할 때 타입을 정하고, 호출된 타입마다 함수 사본을 만든다. nm 에 print_area::<Circle> 과 print_area::<Rect> 가 따로 나온 것이 그 결과였다. 반환 위치 impl Trait 는 사본을 만들지 않고 타입 하나를 숨긴다. dyn Trait 는 값 포인터와 vtable 포인터로 된 fat pointer 이고, 실행 중에 vtable 에서 메서드 주소를 읽는다. area_dyn 에서 확인한 추가 명령은 ldr x1, [x1, #24] 와 br x1 두 줄이었고, 대신 그 안에서는 area 를 인라인할 수 없다. 어떤 trait 를 dyn 으로 쓸 수 있는지도 vtable 을 만들 수 있는지로 정해진다.
여러 타입을 한 곳에 섞거나 반환 타입이 실행 중에 달라지면 dyn 이 필요하다. 그렇지 않을 때만 사본이 늘어나는 비용과 간접 호출 비용을 비교한다. 고르는 일은 함수를 몇 개의 사본으로 컴파일할지, 호출할 구현을 언제 정할지를 정하는 일이라고 봤다.
참고
- Rust 클로저와 iterator: 클로저를 bound 로 받는 Fn·FnMut·FnOnce 와 iterator 어댑터
- Rust 라이프타임: 시그니처의 라이프타임 표기와
T: 'staticbound - Rust 참조와 borrow: 포인터와 길이를 함께 든 슬라이스 참조
&str의 크기 - The Rust Reference — Trait objects
- The Rust Reference — Dyn compatibility
- The Rust Reference — Impl trait
- The Rust Programming Language — Using Trait Objects to Abstract over Shared Behavior
std::ptr::DynMetadata- rustc codegen options — symbol-mangling-version