enumは複数の可能な形態のいずれか1つを表し、各バリアントは異なるデータを保持できます。状態番号と一連のnullableフィールドを持つことと比較して、enumは「どのフィールドがその状態で存在するか」を直接型に組み込むことができます。
Disconnected 接続パラメータなし Connecting address: String Connected peer: String, session: u64 異なる状態のデータを対応するバリアントに格納する 各値は1つのバリアントのみを保持します。型は無意味なフィールドの組み合わせを除外しますが、状態遷移ルールは依然 として実装する必要があります。
状態とデータの共同定義
enum Connection {
Disconnected,
Connecting { address: String } ,
Connected { peer: String , session: u64 } ,
}
fn describe ( state : & Connection) -> String {
match state {
Connection:: Disconnected => " offline" .to_owned ( ) ,
Connection:: Connecting { address } => format! ( " connecting to {address} " ) ,
Connection:: Connected { peer, session } => format! ( " {peer} , session {session} " ) ,
}
}
fn main ( ) {
let states = [
Connection:: Disconnected,
Connection:: Connecting { address: " localhost" .into ( ) } ,
Connection:: Connected { peer: " localhost" .into ( ) , session: 7 } ,
] ;
assert_eq! ( describe ( & states[ 0 ] ) , " offline" ) ;
assert! ( describe ( & states[ 1 ] ) .contains ( " connecting" ) ) ;
assert! ( describe ( & states[ 2 ] ) .contains ( " session 7" ) ) ;
}
これにより、Disconnectedが意図せず未クリーンアップのsessionフィールドを保持することがなくなります。ただし、enum自体はプログラムが任意の状態から別の状態に遷移することを禁止するものではありません。遷移を制限するには、フィールド、メソッド、コンストラクタのエントリポイントをカプセル化する必要があります。
「タグ付き共用体」は有用なセマンティックモデルですが、物理的な記憶域に独立したタグが存在する保証はありません。実際のサイズは最大ペイロード、アライメント、nicheの影響を受けるため、機械的に加算することはできず、Stringなどの所有権を持つフィールドのサイズを無視してはいけません。
Optionのセットを先に書くのではなく、フィールドの組み合わせから型を導出する
status: u8、address: Option<String>、session: Option<u64> を用いて3つの状態を表現する場合、フィールドの組み合わせにおいて「接続済みだがsessionがない」「オフラインなのにsessionが残っている」といった状況が発生する可能性があります。enumは各形態で許可されるデータを直接バリアントに収めるため、呼び出し側が繰り返し確認を行う条件を減らすことができます。
これはしばしば和型(union type)と呼ばれます:値は複数の候補のいずれか1つに属します。structはフィールドの組み合わせをまとめるため、積型(product type)と呼ばれることが一般的です。有限集合の単純な例では、2つのboolは2×2=4通りの組み合わせを持ちます。Pending | Finished(bool) は1+2=3通りの形態を持ちます。ここで計算しているのはセマンティックな値の取り得る範囲であり、レイアウトのバイト数ではありません。
モデリングの選択 表現に適しているもの 追加の制約
Option 通常存在するか、欠落しているか 欠落の理由は通常細分化されない
Result<T, E> 成功結果または報告可能なエラー 失敗の類別はEの設計による
カスタムenum 各状態が異なるペイロードを持つ 遷移、リソース所有権、不変条件
複数の独立フィールド 条件が本当に独立して組み合わせ可能 合法な組み合わせを人為的に禁止しない
存在させたくない組み合わせはどれか
表はペイロードの有無を数えます。3 状態と 2 個の省略可能フィールドの 4 通りで 12 種類ですが、必要なのは 3 種類だけです。組み合わせを選び、enum が余分な形を表せなくする仕組みを確認します。数はサイズでも文字列の全値を含む総数でもありません。
図を準備しています 再読み込み
存在させたくない組み合わせはどれか 独立したフィールドでは 12 通り、この enum では 3 種類のペイロード構造だけを許します。
{"id":"rust-enum-state-space","title":"存在させたくない組み合わせはどれか","summary":"独立したフィールドでは 12 通り、この enum では 3 種類のペイロード構造だけを許します。","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=\"off\" data-i18n=\"off\"></button><button data-mode=\"connecting\" data-i18n=\"connecting\"></button><button data-mode=\"connected\" data-i18n=\"connected\"></button></div><label class=\"check\"><input type=\"checkbox\" id=\"address\"><span data-i18n=\"address\"></span></label><label class=\"check\"><input type=\"checkbox\" id=\"session\"><span data-i18n=\"session\"></span></label><section class=\"panel\"><h3 data-i18n=\"shapes\"></h3><div id=\"space\"></div></section><section class=\"panel\"><h3 data-i18n=\"result\"></h3><div id=\"result\"></div></section><div class=\"copy\"><p id=\"explanation\" role=\"status\"></p><p class=\"reserve\" aria-hidden=\"true\" data-i18n=\"ok\"></p><p class=\"reserve\" aria-hidden=\"true\" data-i18n=\"bad\"></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.table .tr>*{min-height:3.4em}#result{min-height:4em;font:13px 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='off';function draw(){pressed(mode);let a=$('#address').checked,s=$('#session').checked,idx=['off','connecting','connected'].indexOf(mode),valid=(idx===0&&!a&&!s)||(idx===1&&a&&!s)||(idx===2&&a&&s);table('space',[['','0,0','0,1','1,0','1,1'],...['off','connecting','connected'].map((k,i)=>[t(k),...Array.from({length:4},(_,j)=>({text:(i===idx&&j===2*+a+ +s?'● ':'')+((i===0&&j===0)||(i===1&&j===2)||(i===2&&j===3)?'✓':'×'),cls:(i===idx&&j===2*+a+ +s)?'gold':''}))])]);set('result',valid?['Disconnected','Connecting { address }','Connected { peer, session }'][idx]:'—');set('explanation',t(valid?'ok':'bad'));document.body.dataset.valid=valid;}document.querySelectorAll('[data-mode]').forEach(b=>b.onclick=()=>{mode=b.dataset.mode;draw()});inputs(draw);","audio":false,"strings":{"address":"address / peer あり","bad":"通常の struct では格納できますが、この enum では矛盾する状態を構築できません。","connected":"接続済み","connecting":"接続中","heading":"存在させたくない組み合わせはどれか","intro":"status と address・session の有無を変え、独立したフィールドと enum を比べます。","mode":"状態","off":"切断","ok":"選択した組み合わせには、状態と一致するペイロードを持つバリアントがあります。","reset":"リセット","result":"対応する enum","scope":"フィールドの有無だけを数え、String や u64 の全値は数えません。enum 自体は状態遷移を制限しません。","scopeLabel":"モデルの範囲と前提","session":"session あり","shapes":"全フィールドの形状"}}
状態遷移:古い値を消費し、失敗時に誰が所有するかを明確にする
Draft text Queued text + ticket Done receipt Submit Complete 状態の形態はenumで表現され、許可される遷移は関数によってチェックされる テキストは空ではない。完了イベントのticketは現在のタスクと一致しなければならない 無効な遷移は元の状態と理由を返す。フィールドの組み合わせが合法だからといって、任意の状態遷移が合法とは限らない 。
以下の遷移関数はJobを値で受け取ります。成功時は古い状態が消費され、データが新しい状態にムーブされます。失敗時は元の状態とエラーを返し、呼び出し側は編集を続けたり記録したりでき、失敗パスのためにStringをコピーする必要はありません。完了イベントはticketを伴うため、古いタスクの完了イベントが現在のタスクを誤って進行させることを防ぎます。
# [ derive ( Debug, PartialEq ) ]
enum Job {
Draft { text: String } ,
Queued { text: String , ticket: u64 } ,
Done { receipt: String } ,
}
enum Event {
Submit { ticket: u64 } ,
Complete { ticket: u64 , receipt: String } ,
}
fn advance ( job : Job, event : Event) -> Result< Job, ( Job, & 'static str ) > {
match ( job, event) {
( Job:: Draft { text } , Event:: Submit { ticket } ) if ! text.trim ( ) .is_empty ( ) => {
Ok ( Job:: Queued { text, ticket } )
}
( Job:: Queued { ticket, .. } , Event:: Complete { ticket: received, receipt } )
if ticket = = received => Ok ( Job:: Done { receipt } ) ,
( previous, _ ) => Err ( ( previous, " invalid transition" ) ) ,
}
}
fn main ( ) {
let draft = Job:: Draft { text: " report" .into ( ) } ;
let queued = advance ( draft, Event:: Submit { ticket: 7 } ) .unwrap ( ) ;
let ( queued, reason) = advance ( queued, Event:: Complete {
ticket: 6 , receipt: " stale" .into ( ) ,
} ) .unwrap_err ( ) ;
assert_eq! ( reason, " invalid transition" ) ;
assert! ( matches! ( & queued, Job:: Queued { ticket: 7 , .. } ) ) ;
let done = advance ( queued, Event:: Complete {
ticket: 7 , receipt: " stored" .into ( ) ,
} ) .unwrap ( ) ;
assert_eq! ( done, Job:: Done { receipt: " stored" .into ( ) } ) ;
let empty = Job:: Draft { text: String :: new( ) } ;
assert! ( advance ( empty, Event:: Submit { ticket: 8 } ) .is_err ( ) ) ;
}
ここで使用されているガードは、分岐が選択されるかどうかを決定する際に条件をチェックします。条件が失敗しても、後続のマッチングブランチに委ねることができます。完了に成功するとtextは不要になるため、消費された状態とともに古いテキストは解放されます。もしビジネスロジックで全文の監査が必要であれば、それを新しい状態または外部の記録に保存する必要があります。enumが自動的に保持してくれることを期待してはいけません。
この関数は列挙されたローカルな遷移ルールを保証しますが、外部タスクの実行、ticketのグローバル一意性の検証、結果の永続化は行いません。Jobとそのバリアントのコンストラクタがすべて公開されている場合、他のコードは関数を迂回して直接Doneを構築できる可能性があります。外部からの強制エントリポイントにはモジュールカプセル化が必要です。Draftに対して完了操作をコンパイル時に禁止したい場合は、さらに型付きステート(typestate)インターフェースを使用できますが、その代償として、ランタイムでの状態集合と異種コンテナの処理がより複雑になります。
matchは値の取り得る形態に対して網羅性をチェックする
ガードのない網羅的なmatchは、新しいバリアントが追加された際に分岐の追加を促します。すでに_を使用しているmatchはコンパイルを継続できるため、すべてのマッチング箇所が新しいバリアントによってエラーになるとは限りません。公開されているnon_exhaustive enumは、下流が将来の拡張のためにマッチング方法を予約することを要求します。
matchはソースコードの順序に従ってマッチングブランチを探します。ガードは、パターンが成功した後に追加でチェックされるブール条件です。コンパイラは、任意のガードのロジックを完全な網羅性の証明として扱うことは一般的ではありません。match
fn classify ( input : Option< i32 > ) -> & 'static str {
match input {
Some ( value @ 1 .. = 5 ) if value % 2 = = 1 => " small odd" ,
Some ( _ ) => " other number" ,
None => " missing" ,
}
}
fn main ( ) {
assert_eq! ( classify ( Some ( 3 ) ) , " small odd" ) ;
assert_eq! ( classify ( Some ( 2 ) ) , " other number" ) ;
assert_eq! ( classify ( None ) , " missing" ) ;
}
@は、マッチした値を保存しつつサブパターンもチェックします。if letは1つの形態だけを処理する場合に適しており、while letは同じ種類の結果を繰り返し取得する場合に適しています。残りのケースを無視することはインターフェースの意図であるべきであり、構文が短いからといってエラー処理が完了したと見なしてはいけません。
網羅性はカバレッジの証明であり、ビジネスロジックの正当性の証明ではない
Some(x) if x > 0 と Some(x) if x <= 0 はすべてのi32をカバーしているように見えますが、コンパイラは任意のガードの補完関係を普遍証明するものではなく、ガードのない対応するカバーリングブランチが必要です。_ => {} はコンパイルを通過させますが、新しく追加された重要な状態を静かに無視してしまう可能性があります。
or-patternの各ブランチは、同じ名前、互換性のある型、およびバインドパターンを保持する必要があります。例えば、Some(1 | 2) は値のみをテストしますが、Ok(value) | Err(value) はvalueの型が両側で一致していることも要求します。@ はサブパターンのチェックと同時に値をバインドし、任意のサイズのデータのコピーを作成するわけではありません。
fn payload_len ( value : Result< & str , & str > ) -> usize {
match value {
Ok ( text) | Err ( text) => text.len ( ) ,
}
}
fn command ( input : & [u8 ]) -> Option< ( & [u8 ], u8 ) > {
match input {
[ 0x7e , payload @ .. , checksum] => Some ( ( payload, * checksum) ) ,
_ => None ,
}
}
fn main ( ) {
assert_eq! ( payload_len ( Err ( " bad" ) ) , 3 ) ;
assert_eq! ( command ( & [ 0x7e , 1 , 2 , 3 ] ) , Some ( ( & [ 1 , 2 ] [ .. ] , 3 ) ) ) ;
assert_eq! ( command ( & [ 0x7e , 3 ] ) , Some ( ( & [ ] [ .. ] , 3 ) ) ) ;
assert_eq! ( command ( & [ 0x7e ] ) , None ) ;
}
スライスパターンの例は形状と開始マーカーのみをチェックしており、checksumを本当に検証しているわけではありません。パターンは構造を記述するのが得意ですが、ビジネスロジックの関係性は明示的に計算する必要があります。通常のletは反駁不可能なパターンを要求します。マッチする可能性があるSome(x)は、match、if let、またはlet-elseに適しています。
パターンバインドはムーブする場合もあれば、借用する場合もある
fn main ( ) {
let item = Some ( String :: from( " hello" ) ) ;
match & item {
Some ( text) => assert_eq! ( text.len ( ) , 5 ) , None => unreachable! ( ) ,
}
let Some ( text) = item else { return ; } ; assert_eq! ( text, " hello" ) ;
}
&item に対してマッチする場合、マッチングのエルゴノミクスルールにより、内側のバインドはフィールドを借用します。item に対して非Copyフィールドを値でデストラクチャリングすると、所有権が転送されます。let-elseではelseブランチが分岐(return、break、またはpanicなど)することを要求し、それによって後続のパスでパターンが成功したことを前提にすることができます。
パターン内の_はバインドを作成しません。_nameは変数を作成し、値をムーブして所有することができます。Rust 2024では、一部の暗黙的な借用パターン内でref/mutを明示的に書き加える組み合わせに対してより厳しいルールがあり、&value と value のどちらにマッチするかを明確に選択する方が通常は可読性が高くなります。パターン
マッチング対象の式とバインドの型を一緒に見る
入力と書き方 textの型/動作 後続で元のコンテナが保持されるか
match item, Some(text) Stringが値でムーブされる ムーブされた部分は通常使用できない
match &item, Some(text) &String 保持される。借用中は共有ルールに従う
match &mut item, Some(text) &mut String 保持される。借用を通じてフィールドの修正を許可
match item.as_deref() Option<&str> の内側の &str 保持される。文字列の所有権は転送されない
item.take() Optionの元の値を取り出す 元の位置はNoneになる
mut text はバインドを再代入可能にしますが、「&mut Stringを借用した」とは等価ではありません。ref mut text が、対応する値パターンコンテキスト内で可変借用を要求します。Rust 2024では、一部のデフォルト借用パターン内でref/mutを書き加える組み合わせが制限されており、&item または &mut item にマッチすることを明示的に選択し、入力の階層を明確にすることが優先されます。Rust 2024 マッチングルール
fn main ( ) {
let mut item = Some ( String :: from( " hello" ) ) ;
if let Some ( text) = & mut item {
text.push ( ' !' ) ;
}
assert_eq! ( item.as_deref ( ) , Some ( " hello!" ) ) ;
let taken = item.take ( ) .unwrap ( ) ;
assert_eq! ( taken, " hello!" ) ;
assert! ( item.is_none ( ) ) ;
let ignored = Some ( String :: from( " still here" ) ) ;
if let Some ( _ ) = ignored {
assert_eq! ( ignored.as_deref ( ) , Some ( " still here" ) ) ;
}
assert! ( ignored.is_some ( ) ) ;
}
&mut Option<String> から直接Stringを取り出して未初期化の穴を残すことはできません。take() は有効なNoneを挿入することでこの問題を解決します。他の型に対してはmem::replaceを検討できますが、代替値はビジネスロジックで許可された状態であるべきであり、借用エラーを回避するために意味のない状態をでっち上げるべきではありません。Option::take
部分ムーブにおいても、「値全体がまだ使用できるか」と「ムーブされていないフィールドがまだ使用できるか」を区別する必要があります。カスタムDropを持たないstructからStringフィールドをムーブした場合、他のムーブされていないフィールドにアクセスできる可能性があります。struct全体への借用や、完全な値を必要とするメソッドの呼び出しは異なります。カスタムDropを含む型には、フィールドを直接ムーブできないという制限もあります。
OptionとResultは一般的な列挙プロトコルである
通常の参照はnullになり得ませんが、Rustの裸のポインタはnull値を許可するため、「Rustにはnullがない」というのは言い過ぎです。Optionは、正常な安全なインターフェースにおいて欠落を表現し、呼び出し側はunwrapを選択し、Noneの場合にpanicさせることができます。型は自動的に回復策を選択してくれるわけではありません。
fn safe_div ( a : i32 , b : i32 ) -> Option< i32 > { a.checked_div ( b) }
fn main ( ) {
assert_eq! ( safe_div ( 10 , 2 ) , Some ( 5 ) ) ;
assert_eq! ( safe_div ( 10 , 0 ) , None ) ;
assert_eq! ( safe_div ( i32 :: MIN , - 1 ) , None ) ;
}
b == 0のみをチェックすると、最小有符号整数を-1で割った際のオーバーフローを見逃します。呼び出し側が2つの失敗を区別する必要がある場合は、すべての理由をNoneに押し込めるのではなく、類別を持つResultを返すべきです。
Resultは報告可能な失敗を関数の戻り値タイプに組み込みますが、内部にpanicがないことや外部副作用がないことを保証するものではありません。エラー伝播と組み合わせ方については、ResultとOption を参照してください。
公開enumの進化とwireデコード
#[non_exhaustive] は、定義したcrateの外側での使用を主に制約します。crate内では、現在定義されているバリアントに対して完全なマッチングを行うことができます。下流は未知のバリアントブランチを予約する必要がありますが、これはランタイムで任意の整数を合法なenumに変換する許可ではありません。non_exhaustive
wireの状態コードが将来の追加を許可する場合、未知の数値を明確な Unknown(u8) として保存できます。これはRustのenumにおける非法なdiscriminantとは全く異なります。Unknownはすでに定義された合法なバリアントであり、ログ、転送、または後続の処理のために元のコードを保持します。
# [ derive ( Debug, PartialEq ) ]
enum Status { Ready, Busy, Unknown( u8 ) }
impl From< u8 > for Status {
fn from ( code : u8 ) -> Self {
match code {
1 => Self :: Ready,
2 => Self :: Busy,
other => Self :: Unknown( other) ,
}
}
}
fn main ( ) {
assert_eq! ( Status:: from( 1 ) , Status:: Ready) ;
assert_eq! ( Status:: from( 2 ) , Status:: Busy) ;
assert_eq! ( Status:: from( 255 ) , Status:: Unknown( 255 ) ) ;
}
このインターフェースは未知のコードを保持する選択をしていますが、理解して実行する必要がある操作は拒否する必要があります。未知の値を許可しない入力に対しては、TryFromを実装してエラーを返すことができます。transmuteを使用して任意のバイトを有限バリアントenumとして解釈しないでください。レイアウトサイズが同じだからといって、discriminantが有効である証明にはなりません。
enumとmatchの組み合わせは、形態のチェック、フィールドへのアクセス、所有権の転送を1カ所にまとめます。使用する際は、以下の順で確認してください:どの状態に異なるデータが必要か、どの遷移が許可されているか、ブランチが重要なケースを明示的にカバーしているか、バインドはムーブか借用か、未知の入力が合法な型にどう組み込まれるか。これにより、構文の迅速な特定が可能になり、モデルとビジネスロジックの一貫性を保つことができます。