dyn Trait は具体的な実装型を隠し、呼び出し側が合意したインターフェースで操作できるようにします。異なる実装の統一的な扱いや下流での拡張に適します。具体型がコンパイル時に分かっていても、インターフェースやコード量を調整するために選べます。
オブジェクトはヒープ上にあるとは限らない
&dyn Measure 借用。ヒープ割り当ては必須ではない 具体的な値 スタック・ヒープなどの有効領域 対応する実装の vtable 動的に呼び出せるメソッド情報を提供する trait object:データと振る舞いの情報が組み合わさって呼び出しを決定する vtable のフィールド順序やスロットは規定されていないことに注意。内部レイアウトは安定した Rust ABI ではない。
trait Measure {
fn amount ( & self ) -> usize ;
}
impl Measure for usize {
fn amount ( & self ) -> usize { * self }
}
impl Measure for String {
fn amount ( & self ) -> usize { self .len ( ) }
}
fn total ( items : & [& dyn Measure]) -> usize {
items.iter ( ) .map ( | item | item.amount ( ) ) .sum ( )
}
fn main ( ) {
let number = 7 usize ;
let text = String :: from( " abc" ) ;
let items: [ & dyn Measure; 2 ] = [ & number, & text] ;
assert_eq! ( total ( & items) , 10 ) ;
}
ここでは数値と String は局所値で、&dyn Measure はそれらを借用するだけです。Box<dyn Measure> はさらに所有関係を提供します。動的ディスパッチとヒープ割り当ては別の選択で、String 自身のバイトバッファの配置も別の問題です。
trait オブジェクトは動的サイズ型で、通常は参照やスマートポインタを介して扱います。オブジェクトポインタにはデータアドレスと対応する vtable 情報があり、動的な呼び出しは該当メソッドの入口を使います。Trait オブジェクト
「第 3 スロットは必ず fmt」などと仮定して変換・呼び出しをしてはいけません。vtable の内部フィールドやデストラクタ入口は安定 ABI ではなく、異なるコンパイラ版のプラグイン互換性も保証しません。
データとメソッド入口を対応させる
vtable の内部配置を安定した仕様と見なさず、1 つの amount 呼び出しで分派を確認します。usize は値自身、String はバイト長を返します。オブジェクトを変えるとデータと実装が一緒に変わり、呼び出し元は Measure だけに依存します。
図を準備しています 再読み込み
データとメソッド入口を対応させる オブジェクト参照はデータと分派情報を保持し、&dyn Trait のために Box は必須ではありません。
{"id":"rust-dyn-dispatch","title":"データとメソッド入口を対応させる","summary":"オブジェクト参照はデータと分派情報を保持し、&dyn Trait のために Box は必須ではありません。","height":1000,"html":"<h2 data-i18n=\"heading\"></h2><p class=\"intro\" data-i18n=\"intro\"></p><div class=\"presets\" role=\"group\" data-i18n-label=\"mode\"><button data-mode=\"number\" data-i18n=\"number\"></button><button data-mode=\"text\" data-i18n=\"text\"></button></div><svg id=\"map\" class=\"diagram\" viewBox=\"0 0 360 180\" role=\"img\" data-i18n-label=\"heading\"></svg><section class=\"panel\"><h3 data-i18n=\"pair\"></h3><div id=\"pair\"></div></section><div class=\"metrics\"><div><span data-i18n=\"entry\"></span><strong id=\"entry\"></strong></div><div><span data-i18n=\"result\"></span><strong id=\"result\"></strong></div></div><div class=\"copy\"><p id=\"explanation\" role=\"status\"></p><p class=\"reserve\" aria-hidden=\"true\" data-i18n=\"explain\"></p></div><details class=\"scope\"><summary data-i18n=\"scopeLabel\"></summary><p data-i18n=\"scope\"></p></details>","css":".intro{margin:8px 0 18px;color:var(--muted);font-size:14px}.caption,.hint{font-size:12px;color:var(--muted);margin-top:12px}.control{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:6px 12px;align-items:center;margin:14px 0;font-size:13px}.control label{font-size:13px}.control output{color:var(--accent);min-width:5em;text-align:right;font-variant-numeric:tabular-nums}.control input{grid-column:1/-1;width:100%;margin:0}.presets{display:flex;gap:4px;align-items:stretch}.presets button{flex:1 1 0;min-width:0;overflow-wrap:anywhere;font-size:13px}.actions{display:flex;gap:8px;flex-wrap:wrap;margin:14px 0}.actions button{flex:1;min-width:0;font-size:13px;min-height:42px}.copy{display:grid;font-size:14px;margin:16px 0}.copy>*{grid-area:1/1;margin:0}.reserve{visibility:hidden}.scope{margin-top:14px;color:var(--muted);font-size:12px}.scope summary{padding:8px 0;cursor:pointer}.scope p{margin-top:10px}.two{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px;margin:16px 0}.card{border:1px solid var(--rule);border-radius:9px;padding:14px;min-width:0}.card header{font-size:14px;font-weight:600;margin-bottom:10px}.card button{font-size:12px;width:100%;min-width:0}.card small{display:block;font-size:12px;color:var(--muted)}.card code{font-size:12px;overflow-wrap:anywhere}.metrics{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px;margin:16px 0}.metrics>div{border-left:2px solid var(--accent);padding-left:10px;min-width:0}.metrics span{display:block;min-height:3.2em;color:var(--muted);font-size:12px}.metrics strong{font-size:23px;display:block;font-weight:550;overflow-wrap:anywhere;font-variant-numeric:tabular-nums}.formula{border-top:1px solid var(--rule);padding-top:12px;margin-top:14px;font-size:13px;font-variant-numeric:tabular-nums;overflow-wrap:anywhere}.value{font:550 20px ui-monospace,monospace}.legend{display:flex;flex-wrap:wrap;gap:6px 14px;font-size:12px;color:var(--muted);margin:12px 0}.legend span:before{content:'';display:inline-block;width:8px;height:8px;border-radius:2px;background:var(--accent);margin-right:6px}.legend .second:before{background:var(--second)}.check{display:flex;align-items:center;gap:8px;font-size:13px;margin:12px 0}.check input{width:16px;height:16px;flex-shrink:0;accent-color:var(--accent)}select,input[type=text],input[type=number]{background:var(--paper);color:var(--ink);font:inherit;font-size:13px;padding:10px;border:1px solid var(--rule);border-radius:7px;max-width:100%;min-width:0}select{width:100%;min-height:42px}.band{height:20px;display:flex;background:var(--surface);border-radius:4px;overflow:hidden}.band i{height:100%;display:block;background:var(--accent);transition:width .25s}.band i.second{background:var(--second)}button:disabled{cursor:default}.status{font-size:13px;min-height:4.8em}.mono{font-family:ui-monospace,monospace;font-variant-numeric:tabular-nums}.muted{color:var(--muted)}\n@media(max-width:480px){.two{gap:8px}.card{padding:12px 9px}.actions button,.presets button{font-size:12px}.metrics strong{font-size:20px}.metrics{gap:8px}}\n@media(prefers-reduced-motion:reduce){*,*::before,*::after{transition:none!important;animation:none!important}}\n.track-row{margin:16px 0}.track-row>span{display:block;font-size:12px;color:var(--muted);margin-bottom:7px}.track{display:flex;gap:5px;min-width:0}.cell{flex:1;min-width:0;min-height:48px;border:1px solid var(--rule);border-radius:5px;background:var(--surface);display:flex;align-items:center;justify-content:center;text-align:center;padding:5px 3px;font-size:12px;overflow-wrap:anywhere;font-variant-numeric:tabular-nums}.cell.on{background:var(--accent-soft);border-color:var(--accent)}.cell.gold{background:var(--second-soft);border-color:var(--second)}.cell.empty{border-style:dashed;color:var(--muted)}.cell.error{border-color:var(--second);text-decoration:line-through}.choices{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:6px;margin:14px 0}.choices button{min-width:0;padding:10px 4px;font-size:12px;overflow-wrap:anywhere}.choices button[aria-current=true]{border-color:var(--accent);background:var(--accent-soft)}.relation{display:grid;grid-template-columns:minmax(0,1fr) 28px minmax(0,1fr);align-items:center;gap:6px;margin:12px 0}.relation .cell{min-height:72px}.relation>i{text-align:center;font-style:normal;color:var(--accent)}.readout{font-size:13px;white-space:pre-line;min-height:6.4em;overflow-wrap:anywhere}.plot{position:relative;border-left:1px solid var(--rule);border-bottom:1px solid var(--rule);padding:8px 0;margin:18px 0}.plot-row{height:28px;position:relative;margin:4px 0;background:var(--surface)}.plot-row i{position:absolute;inset-block:5px;background:var(--accent);min-width:2px;transition:width .2s,left .2s}.plot-row b{position:relative;padding:4px 6px;font:11px/28px ui-monospace,monospace;background:var(--paper);border-radius:3px}.axis{display:flex;justify-content:space-between;font-size:11px;color:var(--muted)}\n\n/* Action labels must remain readable across locales and narrow embeds. */\n.actions{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px}\n.actions button{overflow-wrap:anywhere;white-space:normal;min-height:58px;padding:8px}\nbutton{overflow-wrap:anywhere}\n@media(min-width:640px){.actions{grid-template-columns:repeat(3,minmax(0,1fr))}}\n\n.metrics span{overflow-wrap:anywhere}\n.panel{border:1px solid var(--rule);border-radius:9px;padding:12px;margin:14px 0;min-width:0}.panel h3{font-size:13px;margin:0 0 10px;color:var(--muted)}.source{font:13px/1.8 ui-monospace,monospace;white-space:pre-wrap;overflow-wrap:anywhere;margin:12px 0}.source mark{background:var(--accent-soft);color:var(--ink);border-bottom:2px solid var(--accent)}.source .fault{background:var(--second-soft);border-color:var(--second)}.diagram{display:block;width:100%;height:auto;max-height:320px;margin:14px 0;overflow:visible}.diagram text{fill:var(--ink);font:12px ui-monospace,monospace}.diagram .edge{stroke:var(--muted);stroke-width:1.5;fill:none}.diagram .edge.on{stroke:var(--accent);stroke-width:3}.diagram .node{fill:var(--surface);stroke:var(--rule);stroke-width:1.5}.diagram .node.on{fill:var(--accent-soft);stroke:var(--accent)}.diagram .node.gold{fill:var(--second-soft);stroke:var(--second)}.log{font:12px/1.8 ui-monospace,monospace;white-space:pre-line;overflow-wrap:anywhere;min-height:7.2em}.table{display:grid;gap:5px;margin:14px 0}.table .tr{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:5px}.table .tr>*{padding:8px 5px;background:var(--surface);border-radius:4px;min-width:0;overflow-wrap:anywhere;font-size:12px}.table .tr .on{background:var(--accent-soft)}.table .tr .gold{background:var(--second-soft)}.choices button{min-height:44px}.metrics strong{min-height:1.6em}.code-line{display:block}.code-line.on{background:var(--accent-soft);border-left:2px solid var(--accent);padding-left:6px}.status-badge{font-size:12px;color:var(--accent)}.tile-grid{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:6px}.tile-grid .cell{min-height:40px}.actions button{min-height:48px}.form-field{display:grid;gap:8px;margin:14px 0;font-size:13px}.form-field input{width:100%;font-family:ui-monospace,monospace}.metrics.three{grid-template-columns:repeat(3,minmax(0,1fr))}.formula{min-height:3.2em}.presets{flex-wrap:wrap}.presets button{flex-basis:25%;min-height:44px}\n\n.budget{display:flex;height:28px;margin:16px 0;background:var(--surface);border-radius:5px;overflow:hidden}.budget i{display:block;background:var(--accent);transition:width .2s}.budget i.gold{background:var(--second)}.intervals{margin:16px 0}.interval{position:relative;height:36px;background:var(--surface);margin:6px 0;border-radius:4px;overflow:hidden}.interval i{position:absolute;height:100%;background:var(--accent-soft);border-left:2px solid var(--accent)}.interval i.gold{background:var(--second-soft);border-color:var(--second)}.interval span{position:relative;z-index:1;font:12px/36px ui-monospace,monospace;padding-left:7px}.table .tr>*{min-height:4.8em}.formula{white-space:pre-line;min-height:7.2em}.actions:has(>button:only-child){grid-template-columns:1fr}.metrics strong{min-height:3.2em}.rangegrid{display:grid;grid-template-columns:repeat(12,minmax(0,1fr));gap:3px;margin:14px 0}.rangegrid .cell{min-height:30px;padding:3px 1px;font-size:10px}.message{min-height:7.2em;white-space:pre-line;font:13px/1.8 ui-monospace,monospace;overflow-wrap:anywhere}\n/* Allow CJK hanging punctuation without overflowing a metric's border box. */\n.metrics>div{padding-right:4px}.metrics span{line-break:anywhere}\n\n.chart-wrap{margin:18px 0}.chart-label{font-size:12px;color:var(--muted);min-height:3.2em}.curve{display:block;width:100%;height:auto;max-height:320px;overflow:visible}.curve text{font:11px ui-monospace,monospace;fill:var(--muted)}.gridline{stroke:var(--rule);stroke-width:1}.metrics strong{font-size:20px;min-height:3.2em}.formula{font:12px/1.8 ui-monospace,monospace;min-height:9em}.readout{min-height:8em}.presets button{flex-basis:30%}.scope p{overflow-wrap:anywhere} .unit-note{font-size:12px;color:var(--muted);margin:10px 0}\n\n.metrics span{word-break:break-all;line-break:strict}.metrics>div{padding-right:6px}\n\n.cell{min-height:72px}.metrics strong{min-height:3.6em}\n\n.metrics strong{font-size:14px;min-height:5em}#pair{min-height:4em;font:13px/1.8 ui-monospace,monospace}","js":"const $=s=>document.querySelector(s);const set=(id,v)=>$('#'+id).textContent=v;const t=k=>viz.t(k);function cells(id,values){$('#'+id).replaceChildren(...values.map(v=>{const e=document.createElement('div');e.className='cell '+(v.cls||'');e.textContent=v.text;e.title=v.title||v.text;return e;}));}function pressed(mode){document.querySelectorAll('[data-mode]').forEach(e=>e.setAttribute('aria-pressed',String(e.dataset.mode===mode)));}const esc=s=>String(s).replace(/[&<>\"']/g,c=>({'&':'&','<':'<','>':'>','\"':'"',\"'\":'''}[c]));const fmt=s=>'{'+[...s].sort().join(', ')+'}';function graph(id,nodes,edges){const el=$('#'+id);el.setAttribute('viewBox','0 0 360 200');el.innerHTML='<defs><marker id=\"arrow-'+id+'\" viewBox=\"0 0 10 10\" refX=\"8\" refY=\"5\" markerWidth=\"5\" markerHeight=\"5\" orient=\"auto-start-reverse\"><path d=\"M 0 0 L 10 5 L 0 10 z\" fill=\"var(--muted)\"/></marker></defs>'+edges.map(e=>{const a=nodes[e[0]],b=nodes[e[1]],dx=b.x-a.x,dy=b.y-a.y,d=Math.hypot(dx,dy)||1;if(edges.some(r=>r[0]===e[1]&&r[1]===e[0])){const nx=-dy/d,ny=dx/d;return '<path class=\"edge '+(e[2]?'on':'')+'\" d=\"M '+(a.x+dx/d*22+nx*12)+' '+(a.y+dy/d*22+ny*12)+' Q '+((a.x+b.x)/2+nx*38)+' '+((a.y+b.y)/2+ny*38)+' '+(b.x-dx/d*25+nx*12)+' '+(b.y-dy/d*25+ny*12)+'\" marker-end=\"url(#arrow-'+id+')\"/>';}return '<line class=\"edge '+(e[2]?'on':'')+'\" x1=\"'+(a.x+dx/d*25)+'\" y1=\"'+(a.y+dy/d*25)+'\" x2=\"'+(b.x-dx/d*28)+'\" y2=\"'+(b.y-dy/d*28)+'\" marker-end=\"url(#arrow-'+id+')\"/>';}).join('')+nodes.map(n=>'<g><circle class=\"node '+(n.cls||'')+'\" cx=\"'+n.x+'\" cy=\"'+n.y+'\" r=\"25\"/><text x=\"'+n.x+'\" y=\"'+(n.y+4)+'\" text-anchor=\"middle\">'+esc(n.name)+'</text>'+(n.sub?'<text x=\"'+n.x+'\" y=\"'+(n.y+43)+'\" text-anchor=\"middle\">'+esc(n.sub)+'</text>':'')+'</g>').join('');}function table(id,rows){$('#'+id).classList.add('table');$('#'+id).replaceChildren(...rows.map(r=>{const row=document.createElement('div');row.className='tr';row.style.gridTemplateColumns='repeat('+r.length+',minmax(0,1fr))';r.forEach(x=>{const c=document.createElement('div');if(typeof x==='object'){c.textContent=x.text;c.className=x.cls||'';}else c.textContent=x;row.append(c)});return row;}));}function band(id,parts,total){$('#'+id).replaceChildren(...parts.map((p,i)=>{const e=document.createElement('i');e.style.width=(100*p.value/total)+'%';e.className=i%2?'gold':'on';e.title=p.name+': '+p.value;return e}));}function intervals(id,items,total){$('#'+id).replaceChildren(...items.map(p=>{const row=document.createElement('div');row.className='interval';const bar=document.createElement('i');bar.style.left=(100*p.start/total)+'%';bar.style.width=(100*(p.end-p.start)/total)+'%';bar.className=p.cls||'';const label=document.createElement('span');label.textContent=p.label;row.append(bar,label);return row;}));}function plot(id,series,xr,yr,opts={}){const e=$('#'+id),X=x=>42+(x-xr[0])/(xr[1]-xr[0])*298,Y=y=>175-(y-yr[0])/(yr[1]-yr[0])*148;let out='<defs><clipPath id=\"clip-'+id+'\"><rect x=\"42\" y=\"27\" width=\"298\" height=\"148\"/></clipPath></defs>';for(let i=0;i<3;i++){let x=xr[0]+i*(xr[1]-xr[0])/2,y=yr[0]+i*(yr[1]-yr[0])/2;out+='<path class=\"gridline\" d=\"M '+X(x)+' 27V175M42 '+Y(y)+'H340\"/><text x=\"'+X(x)+'\" y=\"194\" text-anchor=\"middle\">'+esc(opts.xfmt?opts.xfmt(x):Number(x.toFixed(2)))+'</text><text x=\"36\" y=\"'+(Y(y)+4)+'\" text-anchor=\"end\">'+esc(opts.yfmt?opts.yfmt(y):Number(y.toFixed(2)))+'</text>';}out+='<g clip-path=\"url(#clip-'+id+')\">';for(const s of series){out+='<path fill=\"none\" stroke=\"'+(s.color||'var(--accent)')+'\" stroke-width=\"2.5\" '+(s.dash?'stroke-dasharray=\"5 4\"':'')+' d=\"'+s.pts.map((p,i)=>(i?'L':'M')+X(p[0]).toFixed(2)+','+Y(p[1]).toFixed(2)).join(' ')+'\"/>';}for(const p of opts.points||[])out+='<circle cx=\"'+X(p[0])+'\" cy=\"'+Y(p[1])+'\" r=\"4\" fill=\"var(--second)\" stroke=\"var(--paper)\" stroke-width=\"1.5\"/>';if(opts.cursor!==undefined)out+='<path d=\"M'+X(opts.cursor)+' 27V175\" stroke=\"var(--muted)\" stroke-dasharray=\"3 3\"/>';e.innerHTML=out+'</g>';e.dataset.curves=JSON.stringify(series.map(s=>s.pts));}const curve=(fn,lo,hi,n=120)=>Array.from({length:n+1},(_,i)=>{const x=lo+(hi-lo)*i/n;return[x,fn(x)]});function inputs(draw){document.querySelectorAll('input,select').forEach(e=>{e.addEventListener('input',draw);e.addEventListener('change',draw)});draw()}const n=id=>+$('#'+id).value;const show=(id,v,d=3)=>set(id,Number(v.toFixed(d)));let mode='number';function draw(){pressed(mode);let num=mode==='number';graph('map',[{name:'&dyn',x:55,y:95,cls:'on'},{name:num?'usize':'String',x:200,y:45,cls:'gold'},{name:'vtable',x:200,y:155,cls:'on'},{name:'fn',x:320,y:155,cls:'gold'}],[[0,1,true],[0,2,true],[2,3,true]]);set('pair','data → '+(num?'number: 7':'text: \"rust\"')+'\\nvtable → '+(num?'usize':'String')+' as Measure');set('entry',num?'usize::amount':'String::amount');set('result',num?7:4);set('explanation',t('explain'));}document.querySelectorAll('[data-mode]').forEach(b=>b.onclick=()=>{mode=b.dataset.mode;draw()});draw();","audio":false,"strings":{"entry":"呼び先の実装","explain":"呼び出し元が知るのは Measure です。データとメソッド実装は対応していなければならず、ここではオブジェクトを複製しません。","heading":"データとメソッド入口を対応させる","intro":"具体型を選び、同じ dyn 呼び出しが異なる実装に届く様子を見ます。","mode":"具体オブジェクト","number":"usize:7","pair":"型消去後の参照","reset":"リセット","result":"amount() の戻り値","scope":"論理的な vtable は amount 入口だけを示し、スロット位置、順序、安定 ABI を保証しません。","scopeLabel":"モデルの範囲と前提","text":"String:rust"}}
性能は呼び出しの文脈で評価する
動的呼び出しには通常、間接分派があり、呼び出し境界をまたぐ最適化も制限され得ます。ただし十分な型情報があれば非仮想化されることもあります。ジェネリックは T に特化した最適化に向く一方、インスタンスが増えるとコード量も増え得ます。
enum の match にも分岐があり、配置は最大バリアントに左右され得ます。vtable の有無だけでなく、局所性、オブジェクトサイズ、割り当て回数、実際の計算量を比較します。
動的な境界をどこに置くか
1 万バイトを処理するパーサを考えます。fn parse(&self, input: &[u8]) なら、一度の動的呼び出しの後は具体型を使って内部ループを処理できます。fn next_byte(&mut self) だけを公開すると、各バイトで動的な境界を通る可能性があります。どちらも dyn ですが、呼び出し回数の候補は違います。
すべてのメソッドを巨大な関数にまとめるという意味ではありません。メッセージ、レコードの一群、描画など自然な作業単位を決め、ホットパスを観察します。Vec<Box<dyn Trait>> の個別割り当てやポインタ追跡、enum 配列で大きなバリアントが全要素を広げる費用も区別し、分派だけに帰属させないようにします。
dyn compatibility:消去した型から呼べるメソッド
以前は object safety と呼ばれていた性質です。trait 自身が Self: Sized を要求せず、親 trait も対応する条件を満たす必要があります。関連定数やジェネリック関連型などは利用を制限します。動的に呼べるメソッドは型パラメータを持てず、通常の引数や戻り値で未知の Self に依存したり、不透明な impl Trait を返したり、直接 async fn として宣言したりできません。ライフタイムパラメータは、禁止される型パラメータとは異なります。規則
動的呼び出しに適さないメソッドは where Self: Sized で対象外にでき、必ずしも trait 全体を dyn 非対応にする必要はありません。
trait Label {
fn label ( & self ) -> & str ;
fn duplicate ( & self ) -> Self where Self : Sized;
}
impl Label for String {
fn label ( & self ) -> & str { self }
fn duplicate ( & self ) -> Self { self .clone ( ) }
}
fn main ( ) {
let value = String :: from( " hello" ) ;
let object: & dyn Label = & value;
assert_eq! ( object.label ( ) , " hello" ) ;
assert_eq! ( value.duplicate ( ) , " hello" ) ;
}
通常の関連型は dyn Iterator<Item = u8> のように指定できます。Clone をそのまま dyn Clone にすることはできません。Any の downcast は型の識別であり、複製機能ではありません。オブジェクトを複製するなら Box を返すメソッドなど、適切な抽象を設計します。
関連出力を固定し、戻り値を明確にする
実装型を消去しても、型関係まで全部消えるわけではありません。次の 2 種類のイテレータは内部状態が違っても u8 を生成します。呼び出し側は next が Option<u8> を返すと分かるため、統一して扱えます。
fn total ( input : & mut dyn Iterator< Item = u8 > ) -> u64 {
let mut result = 0 u64 ;
for value in input {
result + = u64 :: from( value) ;
}
result
}
fn main ( ) {
let mut range = 1 u8 .. 4 ;
let mut values = vec! [ 4 u8 , 5 ] .into_iter ( ) ;
assert_eq! ( total ( & mut range) , 6 ) ;
assert_eq! ( total ( & mut values) , 9 ) ;
assert_eq! ( range.next ( ) , None ) ;
}
dyn Iterator だけでは Item が未指定です。dyn Iterator<Item = u8> としても String を生成するイテレータは同じ位置に入りません。統一するのは反復プロトコルと出力型で、内部実装は異なります。合計値は u64 の範囲内なので、業務に応じたオーバーフロー処理も必要です。
メソッド制限は、呼び出し側がシグネチャを確定できるかから考えられます。Self を返すには隠された具体型が必要で、型パラメータ付きメソッドは呼び出し側が多様なインスタンスを選べます。where Self: Sized はそれらを具体型の呼び出しに残し、オブジェクトには trait の一部だけを公開します。除外したメソッドを dyn で呼べるようにする指定ではありません。
オブジェクトのライフタイムとスレッド制約
一般的な型の位置では Box<dyn Trait> のオブジェクトライフタイムは 'static が既定です。任意の短い借用を格納できるわけではなく、必要なら Box<dyn Trait + 'a> と書きます。Box がプログラム終了まで生きるという意味ではなく、内部の借用を制約します。
スレッドをまたぐ場合は dyn Trait + Send や + Sync を明示的に検討します。元の型が持つ auto trait が、消去後にすべて残るわけではありません。外側が Box か Arc かによっても条件が変わります。
コンテナの所有と全データの所有は別
Box<dyn Text + 'a> 所有するオブジェクトを破棄 Borrowed<'a> ヒープ上に &str を格納 String バッファ source が所有 所有 借用 object の使用後に source を解放 制約は文字列を複製せず、source の寿命も延ばさない 所有と借用を区別。vtable は省略し、配置は縮尺どおりではない。 所有するラッパと借用データ
trait Text {
fn text ( & self ) -> & str ;
}
struct Borrowed < 'a > ( & 'a str ) ;
impl Text for Borrowed < '_ > {
fn text ( & self ) -> & str { self .0 }
}
fn make < 'a > ( source : & 'a str ) -> Box< dyn Text + 'a > {
Box :: new( Borrowed( source) )
}
fn main ( ) {
let source = String :: from( " borrowed text" ) ;
{
let object = make ( & source) ;
assert_eq! ( object.text ( ) , " borrowed text" ) ;
}
assert_eq! ( source, " borrowed text" ) ;
}
Box は Borrowed を破棄しますが、そのフィールドは source の借用です。object が source の有効範囲を逃げると借用検査に拒否されます。戻り値を適切な制約のない Box<dyn Text> に変えても 'static へ延長できません。ラッパが String を所有する設計も可能ですが、データの所有関係を変えます。
型 区別する制約
&'a (dyn Text + 'b)外側の参照の有効期間と、隠れた実装内の借用の制約
&'a dyn Text通常は外側の参照からオブジェクトの境界を導く
Box<dyn Text + 'a>Box はオブジェクトを所有し、内部には 'a を満たす借用を含められる
Box<dyn Text>他の制約がない型位置では通常 'static。局所式では推論も働く
省略を一律に「dyn は 'static」と説明しないようにします。包含する型、trait 自身の制約、式の文脈が既定規則に関係します。借用インターフェースでは明示した方が読みやすい場合があります。既定オブジェクトライフタイム
Arc は所有を共有し、内部の同期までは提供しない
Arc<dyn Text + Send + Sync> はスレッド間で共有可能なインターフェースを表せますが、実際の型も制約を満たす必要があります。参照カウントが原子的でも RefCell の内部状態は同期されず、データアクセスには適切な同期が必要です。Arc のスレッド安全性
型消去時には後で必要な制約を残します。Box<dyn Text> を受け取った後、元が String だったというだけで Box<dyn Text + Send> にはできません。Send はスレッド間の値の移送、Sync は参照の共有、'static は制約付き借用の有無という別の問題です。
親 trait へインターフェースを狭める
Rust 1.86 から trait upcasting が安定化し、子 trait のオブジェクトを親 trait のオブジェクトへ変換できます。汎用関数は基本インターフェースに依存し、拡張機能は必要な呼び出し側だけが使えます。Rust 1.86
trait Named {
fn name ( & self ) -> & str ;
}
trait Detailed : Named {
fn revision ( & self ) -> u32 ;
}
struct Document ;
impl Named for Document {
fn name ( & self ) -> & str { " guide" }
}
impl Detailed for Document {
fn revision ( & self ) -> u32 { 3 }
}
fn display ( value : & dyn Named) -> String {
format! ( " name={} " , value.name ( ) )
}
fn main ( ) {
let document = Document;
let detailed: & dyn Detailed = & document;
let named: & dyn Named = detailed;
assert_eq! ( detailed.revision ( ) , 3 ) ;
assert_eq! ( display ( named) , " name=guide" ) ;
}
これは見えるインターフェースを狭める変換で、Document 型を復元したり逆変換を許したりしません。非 auto trait を直接 2 つ並べた dyn Read + Write は使えません。両方を継承する基本 trait を定義し、適切に実装します。1 つの基本 trait には Send、Sync などの auto trait を追加できます。オブジェクト型の制約
具体型の識別が必要なら Any を設計に使えますが、'static を要求するため任意の短い借用を持つオブジェクトには適しません。downcast が頻繁なら、必要な操作を共通 trait に表せないか確認します。Any
enum、ジェネリック、dyn の選択
方法 実装集合を決める側 利点 検討する費用
enum + match 型の定義者がバリアントを列挙 網羅性検査、状態の集中管理 追加による match と配置への影響
ジェネリック T: Trait 呼び出し側が具体型を選択 十分な型情報、型別の最適化 インスタンス数、型の複雑さ
dyn Trait 契約を満たす実装者 異種オブジェクトと拡張性 分派、ライフタイム、dyn compatibility
集合が開かれているか、所有が必要か、動的呼び出しが適切かを検討します。単に型がコンパイル時に分かるかより有用な判断軸です。関連する仕組みは単相化 を参照してください。