Workspace は、関連する複数のパッケージが依存関係の解決記録とビルド管理のエントリポイントを共有できるようにします。コアライブラリ、コマンドラインツール、サーバーサイドが共に進化していくプロジェクトに適していますが、依存バージョンの重複を自動的に解消するわけでも、メンバを一緒に公開することを強制するわけでもありません。
分割設計では、インターフェースと責任を優先してください。ある crate の変更が別の crate に影響を与えるべきか、独立してテストできるか、外部に公開する必要があるか。小さすぎる crate が増えすぎると、保守コストやコンパイルの境界コストが増加します。
ルート Cargo.toml と Cargo.lock メンバ一覧、継承設定、統一された解決記録 calc-core:ライブラリパッケージ 再利用可能なビジネスインターフェースを維持 demo-cli:バイナリパッケージ path 依存で calc-core に依存 Workspace は共有管理エントリポイントを提供し、メンバは独立したパッケージ のままです 共有される target ディレクトリは、各依存が一度だけコンパイルされることや、依存グラフにバージョンが一つしかない ことを保証しません。
完全な双メンバ構成のプロジェクト
ルートの Cargo.toml:
[workspace]
members = ["crates/calc-core", "crates/demo-cli"]
default-members = ["crates/demo-cli"]
resolver = "3"
[workspace.package]
version = "0.1.0"
edition = "2024"
[workspace.dependencies]
calc-core = { path = "crates/calc-core", version = "0.1.0" }
ルートには [workspace] しかなく、これは仮想マニフェストです。resolver=3 は Rust 2024 と同時に導入され、Rust/Cargo 1.85 以降が必要です。仮想 workspace には、推論に使用できるルートのパッケージの edition がないため、明示的に選択する必要があります。resolver=3 は rust-version に非互換な依存に対して適切なフォールバック戦略を採用しますが、最低ツールのチェーンでの実測に代わるものではありません。依存関係パーサー
crates/calc-core/Cargo.toml:
[package]
name = "calc-core"
version.workspace = true
edition.workspace = true
crates/calc-core/src/lib.rs:
pub fn doubled ( value : u32 ) -> Option< u32 > { value.checked_mul ( 2 ) }
crates/demo-cli/Cargo.toml:
[package]
name = "demo-cli"
version.workspace = true
edition.workspace = true
[dependencies]
calc-core.workspace = true
crates/demo-cli/src/main.rs:
fn main ( ) {
assert_eq! ( calc_core:: doubled( 21 ) , Some ( 42 ) ) ;
assert_eq! ( calc_core:: doubled( u32 :: MAX ) , None ) ;
println! ( " 42" ) ;
}
cargo run - p demo-cli
cargo check -- workspace
cargo test -- workspace
cargo metadata -- no-deps -- format-version 1
ここで checked_mul はオーバーフローを明示的に処理しており、リリース時とデバッグ時のデフォルトの算術チェックの違いをビジネスインターフェースに持ち込まないようにしています。
実際のライブラリテストでメンバの選択を観察する
calc-core/src/lib.rs の後に、以下のテストを追加します。境界値は u32::MAX / 2 を明確に使用し、デフォルトのオーバーフローチェックスイッチに依存せずに、最大で 2 倍にできる値と、それに隣接するオーバーフローする値を検証します。
# [ cfg ( test ) ]
mod tests {
use super :: doubled;
# [ test ]
fn boundary ( ) {
assert_eq! ( doubled ( 0 ) , Some ( 0 ) ) ;
assert_eq! ( doubled ( u32 :: MAX / 2 ) , Some ( u32 :: MAX - 1 ) ) ;
assert_eq! ( doubled ( u32 :: MAX / 2 + 1 ) , None ) ;
}
}
workspace ルートで cargo test を実行すると、default-members によって demo-cli のみが選択されます。calc-core は依存関係としてコンパイルされますが、そのライブラリのユニットテストはそれによって実行されません。cargo test -p calc-core または cargo test --workspace を使用して初めて、boundary テストの実行を確認できます。これは、「アプリケーションビルドがコアライブラリに依存している」ことと「コアライブラリのテストがカバーされている」ことが互いに代替できない理由を説明しています。
依存をビルドすると単体テストも動くか
依存関係は同じで、コマンドによって各パッケージのテスト target の選択が変わります。既定では CLI 経由で calc-core を使っても、calc-core の #[test] は実行しません。-p calc-core や --workspace に変えて対象の変化を確認します。
図を準備しています 再読み込み
依存をビルドすると単体テストも動くか default-members=[demo-cli] なら既定のテストは CLI を選び、依存の calc-core をビルドしてもその単体テストは動きません。
{"id":"rust-workspace-test-selection","title":"依存をビルドすると単体テストも動くか","summary":"default-members=[demo-cli] なら既定のテストは CLI を選び、依存の calc-core をビルドしてもその単体テストは動きません。","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=\"default\" data-i18n=\"default\"></button><button data-mode=\"core\" data-i18n=\"core\"></button><button data-mode=\"all\" data-i18n=\"all\"></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=\"packages\"></h3><div id=\"packages\"></div></section><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.table .tr>*{min-height:4em}","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='default';function draw(){pressed(mode);let c=mode!=='default',a=mode!=='core';graph('map',[{name:'CLI',x:90,y:100,cls:a?'on':''},{name:'core',x:270,y:100,cls:c?'on':'gold'}],[[0,1,a]]);table('packages',[['', 'demo-cli','calc-core'],[t('selected'),a?'✓':'—',c?'✓':'—'],[t('built'),'—',a?'✓':'—'],[t('unit'),a?'✓':'—',c?'✓':'—']]);set('explanation',t('explain'));}document.querySelectorAll('[data-mode]').forEach(b=>b.onclick=()=>{mode=b.dataset.mode;draw()});draw();","audio":false,"strings":{"all":"test --workspace","built":"通常依存のビルド","core":"test -p calc-core","default":"cargo test","explain":"通常ライブラリをビルドすることと、そのテスト target をビルド・実行することは別です。","heading":"依存をビルドすると単体テストも動くか","intro":"仮想 workspace のルートでコマンドを選び、選択パッケージとビルド依存を比べます。","mode":"コマンド","packages":"ビルドとテストの対象","reset":"リセット","scope":"本文の 2 メンバーで CLI が core に依存します。lib/bin の単体テスト選択を示し、全 doctest や統合 target は列挙しません。","scopeLabel":"モデルの範囲と前提","selected":"明示選択","unit":"単体テスト実行"}}
継承は明示的な選択であり、ルート設定が自動的にすべてを上書きするわけではありません
メンバは workspace=true を通じて、対応する継承項目を選択する必要があります。workspace.dependencies の path は workspace ルート相対で解決されます。メンバの dependencies に直接記載された path はメンバのマニフェスト相対です。バージョン要件と path が同時に存在する場合、ローカルパッケージも要件を満たす必要があり、公開のセマンティクスにはレジストリバージョンも関与します。
メンバは継承された依存関係に feature を追加できますが、ルートで有効にされた feature はメンバによって任意に削除されることはありません。共通宣言によって設定の重複を減らせますが、他の推移的な依存関係が別の非互換バージョンを持ち込むのを阻止することはできません。ワークスペース
ルートの profiles や patch などの設定はワークスペースビルドに影響します。profile をメンバファイルに配置して独立して有効になることを期待しても、通常は無視される旨のヒントが返されます。lints や package のメタ情報なども、対応する継承構文に従って明示的に選択する必要があります。
lint 継承にもメンバの接続が必要
ルートマニフェストに以下を追加:
[workspace.lints.rust]
unsafe_code = "forbid"
この制約に従う必要がある各メンバに以下を追加:
[lints]
workspace = true
これは、純粋なビジネス crate 間で unsafe を共同で禁止するのに適しています。これは依存関係のソースコードにグローバルポリシーを適用するものではなく、外部依存関係には独自のコンパイルコンテキストがあり、ネイティブライブラリの安全性はこの lint によって証明されるものではありません。もし専用の FFI メンバが実際に unsafe の境界を担当している場合、ルートテーブルがすべてのメンバを無条件で上書きすると誤解するのではなく、明確なチェック方法と設定をそれに与えるべきです。ワークスペース継承設定
共有ロックファイルは、すべての依存関係が 1 つしかないことを意味しません
Cargo.lock は、foo 1.x と foo 2.x を同時に記録できます。異なるパッケージバージョンに由来する型は異なるアイデンティティを持ち、たとえ同名の構造体のフィールドが似ていたとしても、互いに渡せるわけではありません。cargo tree -d はこれらの状況の発見に役立ち、cargo tree -i はさらに参照元を探すことができます。
target ディレクトリも単に共有されたビルド成果物の場所です。ターゲットアーキテクチャ、プロファイル、feature の集合、ホストビルド依存関係、およびコンパイルオプションが異なる場合、異なるコンパイルユニットが発生する可能性があります。「共有キャッシュ」からすべての依存関係が一度だけコンパイルされることを推論することはできません。
コマンドの適用範囲は明確に記述する
仮想 workspace ルートで -p を指定しない場合、default-members がデフォルトのメンバ選択を制御します。--workspace は明示的にすべてのメンバを選択します。指定されたパッケージには -p を使用でき、パッケージ内に複数のバイナリがある場合は --bin をさらに使用します。
cargo test --workspace のテストターゲット、ドキュメントテスト、および通常のビルドは、完全に同じ設定ではありません。公開チェックは、公開準備が整った特定のパッケージに対して実行すべきであり、ワークスペースビルドが成功したからといって、各パッケージを独立してパッケージ化した場合に正しいファイルと解決可能な依存関係が含まれるとは限りません。
ルートディレクトリ cargo test default-members: demo-cli cargo test --workspace メンバ: demo-cli + calc-core calc-core はライブラリ依存としてビルド 其中的な boundary ユニットテストは実行されない calc-core のテストターゲットもビルド boundary ユニットテストを実行 まずパッケージを選択し、次にターゲットを選択;依存関係のコンパイルは依存関 係のテストを意味しません 図はこのページの双メンバ構成を使用しています。-p、--lib、--bin、--test はそれぞれ異なる選択レベルを制御します。
コマンド (workspace ルートで) 明示的に選択するもの これによって推論できないもの
cargo check デフォルトメンバ demo-cli 他のメンバのすべてのターゲットがチェック済みであること
cargo test -p calc-core --lib コアライブラリのユニットテストターゲット CLI、統合テスト、ドキュメントテストがすべて実行済みであること
cargo test --workspace 各メンバのデフォルトテストセット 各 feature と各ターゲットプラットフォームで通過していること
cargo check --workspace --all-targets メンバのライブラリ、バイナリ、テスト、例、ベンチマークなどのターゲット ドキュメントテストが実行済みであること、またはバイナリがリンク済みであること
cargo test --workspace --exclude demo-cli CLI を除外してメンバを選択 他のパッケージに依存するコードが決してビルドされないこと
ここで言う Cargo ターゲット(lib/bin/test などのビルドターゲット)は、--target で指定されるプラットフォームのトライプレットの 2 つの次元です。「なぜまだこのパッケージをコンパイルしているのか」を調査する際は、まずそれが依存関係として出現しているかどうかを確認します。「なぜこのテストが漏れているのか」を調査する際は、パッケージとテストターゲットが選択されているかどうかを確認します。テストターゲットの選択
patch は、あるソースに対して候補パッケージを補足するもの
レジストリ内の codec パッケージにローカル修正が必要だと仮定します。ルートマニフェストに以下のように記述できます:
[patch.crates-io]
codec = { path = "vendor/codec" }
これは、vendor/codec が実際に codec という名前で、依存関係の制約を満たすバージョンのパッケージを含んでいることを要求します。patch はすべての同名バージョンを無条件に上書きするわけではありません。ロックファイルと候補バージョンの選択により、採用されない場合があるため、Cargo のヒント、cargo tree、およびロックファイルを確認し、必要に応じてそのパッケージに対して解析を更新してください。
また、「すべての依存関係の要件が完全に一致する必要がある」場合にのみ使用できるものでもありません。複数の互換範囲が同じバージョンに解決される場合もあれば、非互換バージョンが引き続き共存する場合もあります。別のメジャーバージョンを置き換えるには、適切な候補を個別に提供する必要があり、マニフェストのバージョン番号だけを変更して API を保守しないままにすることはできません。
ライブラリ自身が宣言した patch は、ダウンストリームアプリケーションのルート設定に自動的に適用されるわけではありません。ローカルでの修正検証のみを行う場合は、使用元と削除条件を記録してください。公開する場合は、ダウンストリームが正式な依存関係のソースから必要なバージョンを取得できることを確認してください。依存関係のオーバーライド
境界を用いてビルドの結合を減らす
コアライブラリは安定した型と明確なエラーをできるだけ公開し、CLI は引数と出力を担当してください。1 つの定数を共有するために、ネットワークランタイムやビルドジェネレータをすべてのメンバに持ち込まないでください。パブリック依存関係の再エクスポート、feature の和集合、および build.rs の出力は結合を拡大するため、インターフェースを変更する際に一緒に評価してください。
生成コードとネイティブビルドの責任については Cargo.toml を、条件分岐の検証については cfg を参照してください。
独立したパッケージ化は、ワークスペース内では見えない依存関係を露呈する
外部依存関係のない calc-core でローカルパッケージ化を練習してください:
cargo package - p calc-core -- list
cargo package - p calc-core
1 行目はパッケージに含まれるファイルをチェックし、2 行目は .crate を生成し、デフォルトで解凍してビルド検証を行います。リストを確認する際は、src が存在するかどうかだけでなく、実行またはビルドに必要なテンプレート、ヘッダーファイル、設定サンプルに注目してください。build.rs が workspace 外の隣接ディレクトリに依存している場合、リポジトリ内でのビルドは成功するかもしれませんが、独立したパッケージ化後にはそれらの入力がなくなります。
パッケージ化時に Cargo はマニフェストを正規化し、継承フィールドを処理し、workspace、patch などのルート設定を削除します。demo-cli にとって、calc-core の path はローカル開発の位置を解決するだけであり、version がレジストリ依存関係を記述します。正式な配布では、必要なバージョンが対応するソースで取得可能であることを確保する必要があります。2 つのパッケージを同じリポジトリに配置しても、公開後の CLI がその相対パスに自動的にアクセスできるわけではありません。cargo package の処理手順
これらのメンバが内部でのみ一緒にビルドされる場合は、誤った公開を防ぐために、対応するパッケージで publish=false を設定できます。これは通常のローカル path 依存関係には影響しません。個別に公開する場合は、コアライブラリのパブリック API を中心に互換バージョンを決定し、使用側の要件を更新してください。統一された継承 version は単に値を統一するだけであり、セマンティックな互換性を自動的に分析したり、公開の順序を手配したりするものではありません。
新しいメンバの接続時には、実際の使用チェーンに沿って確認する
新しいサービスパッケージを追加した後、まず cargo metadata 内の workspace_members と workspace_default_members が期待どおり是否符合するかを確認します。次に、コアライブラリへの通常の依存関係、テスト専用依存関係、およびビルド依存関係が正しいテーブルに配置されているかどうかを確認します。最後に、ユーザーの実際のエントリポイントからエンドツーエンドのユースケースを実行します。例えば、CLI 引数をビジネス数値に変換し、doubled を呼び出し、None を理解可能なエラーに変換します。
ディレクトリの分割は、対応するインターフェースの境界がある場合にのみ価値を生みます。コアライブラリが Option を返すことは、この小さな例の完全な契約です。将来的に不正な入力、オーバーフロー、およびリソースエラーを区別する必要がある場合は、明確なエラー型にアップグレードし、各エントリが表示を担当するようにしてください。コアレイヤーが直接印刷したりプロセスを終了したりすることを避け、Web サービスやテストが関数を再利用しても、エラーレスポンスの方法を自由に決定できるようにしてください。