Cargo.toml はパッケージのビルド契約であり、どのターゲットを生成するか、依存関係をどこから取得するか、どのオプション機能(feature)を有効にするか、そしてどのようなビルド設定を使用するかを宣言します。Cargo.lock は依存関係解決の結果を記録するもので、両者は互いに代替できません。
1つのパッケージには、1つのライブラリターゲットと、複数のバイナリ、テスト、またはサンプルターゲットを含めることができます。crate は Rust のコンパイル単位であり、package、crate、workspace を同義語として扱うべきではありません。
Cargo.toml 依存元の宣言、バージョン範囲、feature、ターゲットの指定 1 Cargo による依存関係グラフの解決 適用される feature をマージし、制約を満たすパッケージバージョンを選択 2 Cargo.lock 今回の解決で使用されたバージョン、ソース、検証情報を記録 3 コンパイルとリンク ツールチェーン・対象・ネイティブ依存・構築入力にも依存 4 ビルドの再現性:制約、解決結果、環境はどれも欠かせません ロックファイルは依存関係の選択を固定しますが、OS全体やツールチェーンを自動的にロックするものではありません。
バージョン文字列は通常、範囲指定です
表記 許可される一般的な正式バージョンの範囲
"1.2.3" または "^1.2.3" >=1.2.3 かつ <2.0.0
"=1.2.3" 正確に 1.2.3
"~1.2.3" >=1.2.3 かつ <1.3.0
"0.2.3" >=0.2.3 かつ <0.3.0
"0.0.3" >=0.0.3 かつ <0.0.4
したがって、"1.2.3" は固定バージョンを意味するものではありません。プレリリースバージョンには追加のマッチングルールがあり、この正式バージョンの表をすべての -alpha/-beta 版にそのまま適用しないでください。依存関係のバージョン構文
バージョン制約が SemVer の範囲に準拠していても、Cargo がアップストリームの各 API が実際に互換性があるかどうかをチェックするわけではありません。ロックファイル内の既存バージョンが依然として制約を満たしている場合、通常のビルドではそれを継続して使用するのが一般的です。依存関係を更新する際は、ロックファイルを削除して「運試し」するのではなく、解決変更を明示的に確認すべきです。
Cargo.lock は、アプリケーションおよびライブラリリポジトリが CI 結果を再現するのに役立ちます。現在の Cargo ガイドラインでは、不明確な場合はロックファイルをコミットすることを推奨しています。「すべてのライブラリでロックファイルをコミットしない」というのはもはや適切な一般則ではありません。ただし、ダウンストリームがライブラリを使用する場合、その依存関係グラフはダウンストリーム側で解決され、そのライブラリリポジトリ自身の lock ファイルによる強制制限は受けません。マニフェストとロック
バージョン、ソース、インポート名は3つの次元です
[dependencies]
json_codec = { package = "serde_json", version = "1" }
ここで依存関係にあるパッケージは依然として serde_json ですが、Rust コードでは json_codec パスを使用します。package フィールドはパッケージ名を特定し、表のキーが依存関係を現在のコードでの名前として決定します。これが、マクロやプロシージャルマクロがユーザー側の依存関係名を安易にハードコーディングできない理由でもあります。
依存関係のソース 解決時に固定されるもの 維持すべきもの
registry + バージョン範囲 要件を満たす公開バージョン lock 内の実際の選択と検証情報
git + rev 指定されたリポジトリのコミット そのコミットへのアクセス元とビルド環境
git + branch ブランチ要件、lock には解決されたコミットを記録 ブランチのその後の移動は、既存の lock の自動更新にはなりません
path ローカルパッケージの場所とマニフェスト ローカルソースファイルの内容、lock はその内容のスナップショットを保存しません
path と version は組み合わせて使用できます。ローカル開発ではパスを使用しつつ、ローカルパッケージのバージョンが制約を満たすことを検証し、registry への公開後の依存関係に対してバージョン要件を提供します。これは「ローカルビルド時にいつでも registry に自動的にフォールバックする」汎用メカニズムではありません。パス指定パッケージのソースファイルを変更すると、Cargo.lock が変更されていなくても、ビルド成果物が変化する可能性があります。複数ソースの依存関係
依存関係の種類によって利用可能な側が決まります
設定 主な使用箇所
dependencies 通常のライブラリ/プログラムコード
dev-dependencies テスト、サンプル、ベンチマークなどの開発用ターゲット
build-dependencies ホスト上で実行される build.rs
target.'cfg(...)'.dependencies ターゲットの条件を満たす場合の通常の依存関係
同じ依存関係が build 依存関係と通常の依存関係の両方に現れる場合、ホスト用とターゲット用にそれぞれコンパイルされる可能性があります。名前が同じだからといって、すべての feature やビルド成果物を共有すると仮定しないでください。ターゲット条件を、Cargo のオプション依存関係のメカニズムの代わりとして feature で代替すべきではありません。
feature は組み合わせ可能な能力です
以下は、完全な小規模プロジェクトの Cargo.toml です。
[package]
name = "feature-demo"
version = "0.1.0"
edition = "2024"
[features]
default = []
json = ["dep:serde_json"]
[dependencies]
serde_json = { version = "1", optional = true }
src/main.rs:
# [ cfg ( feature = " json" ) ]
fn output ( ) -> String {
serde_json:: json! ( { " ready" : true } ) .to_string ( )
}
# [ cfg ( not ( feature = " json" ) ) ]
fn output ( ) -> String {
" ready=true" .into ( )
}
fn main ( ) { println! ( " {} " , output ( ) ) ; }
cargo run -- no-default-features
cargo run -- features json
cargo tree - e features -- features json
dep:serde_json はオプション依存関係を明示的に有効にし、単に依存関係の名前だけで同名の feature が自動的に公開されるのを防ぎます。feature の加法性は、まず依存関係解決と API 設計の原則です。同一パッケージに対する適用リクエストは通常、和集合としてマージされます。これは、cfg(not(feature=...)) が構文上、特定のコードブロックの削除を禁止するわけではないことを意味します。Cargo Features
依存関係 A がデフォルト feature を無効にしても、依存関係 B が同じパッケージのデフォルト feature を再度有効にすることを妨げるものではありません。公開ライブラリの機能はできるだけ組み合わせ可能であるべきです。相互に排他的な feature は compile_error! で検証できますが、それにより通常の依存関係マージでそのライブラリを使用できなくなる可能性があります。resolver のバージョンとビルドコンテキストが、どの feature セットを分離して解決するかを決定し、「ワークスペース全体が無条件にすべてマージされる」と一般化してはなりません。
依存元 A default-features = false 依存元 B default を有効化、default は std を含む 同じ適用解決コンテキスト内の shared 自分の依存関係エッジのデフォルト機能を無効にしても、他の依存関係エッジを無 効化しない 最終的な feature の和集合には依然として default と std が含まれる 図は同一パッケージインスタンスを対象としています。resolver はバージョン、依存関係の種類、ターゲットなどのルール に基づいてコンテキストを区別します。
依存関係エッジに沿って「誰がそれを有効にしたか」を追跡する
ビルド中に予期しない std や特定のバックエンドが現れた場合、現在のパッケージの default-features のみをチェックすべきではありません。まず cargo tree -e features -i パッケージ名 を使用して逆方向の依存関係を確認し、通常の依存関係、開発用ターゲット、またはビルド側のコンテキストのいずれかが要件を提示していないかを確認してください。
--no-default-features もまた、「依存関係グラフ全体でデフォルト機能を無効にする」わけではありません。各依存関係のデフォルト機能は、それぞれの宣言とマージルールによって依然として決定されます。真の最小ビルドをサポートするには、最小限の feature 組み合わせで個別にコンパイルする必要があり、--all-features を1回実行しただけで全構成を網羅したと主張してはいけません。
既定 feature を再び有効にしたのは誰か
同じ依存への 2 つの要求を和集合にすると、default を無効にしても std が残る理由が分かります。B の既定を残して A を切り替え、B も解除すると std が消えます。実際は版と resolver の文脈を確認してから cargo tree で feature の要求元を辿ります。
F resolved = closure ( F A ∪ F B )
図を準備しています 再読み込み
既定 feature を再び有効にしたのは誰か A が既定を無効にしても B の要求を拒否せず、適用される要求は和集合になります。
{"id":"rust-feature-union","title":"既定 feature を再び有効にしたのは誰か","summary":"A が既定を無効にしても B の要求を拒否せず、適用される要求は和集合になります。","height":1000,"html":"<h2 data-i18n=\"heading\"></h2><p class=\"intro\" data-i18n=\"intro\"></p><label class=\"check\"><input type=\"checkbox\" id=\"ad\"><span data-i18n=\"ad\"></span></label><label class=\"check\"><input type=\"checkbox\" id=\"aj\" checked><span data-i18n=\"aj\"></span></label><label class=\"check\"><input type=\"checkbox\" id=\"bd\" checked><span data-i18n=\"bd\"></span></label><label class=\"check\"><input type=\"checkbox\" id=\"bj\"><span data-i18n=\"bj\"></span></label><section class=\"panel\"><h3 data-i18n=\"requests\"></h3><div id=\"requests\"></div></section><div class=\"track-row\"><span data-i18n=\"resolved\"></span><div id=\"resolved\" class=\"track\"></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#requests{min-height:8em}.track{flex-wrap:wrap}.cell{flex-basis:20%}","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)));function draw(){let req=p=>[...($('#'+p+'d').checked?['default','std']:[]),...($('#'+p+'j').checked?['json','alloc']:[])],a=req('a'),b=req('b'),u=new Set([...a,...b]);table('requests',[['A','{'+a.join(', ')+'}'],['B','{'+b.join(', ')+'}']]);cells('resolved',['default','std','json','alloc'].map(x=>({text:x,cls:u.has(x)?'on':'empty'})));set('explanation',t('explain'));document.body.dataset.features=[...u].sort().join(',');}inputs(draw);","audio":false,"strings":{"ad":"A:default-features","aj":"A:json","bd":"B:default-features","bj":"B:json","explain":"ある辺の既定を無効にするのは、その辺で要求しないという意味で、依存グラフ全体での禁止ではありません。","heading":"既定 feature を再び有効にしたのは誰か","intro":"同じ依存への A・B の要求を変え、feature の和集合を確認します。","requests":"依存辺の要求","reset":"リセット","resolved":"最終的な feature 集合","scope":"同じ版の通常のターゲット依存です。default=[std]、json=[alloc] とし、host/build/dev の文脈を無条件には統合しません。","scopeLabel":"モデルの範囲と前提"}}
profile はトレードオフを制御し、最適解を保証するものではありません
dev はデフォルトでデバッグとインクリメンタルビルドに偏り、release はデフォで opt-level=3 です。現在のデフォルトの release では lto=false であり、明示的なクロス crate の lto="thin" ではありません。false は特定の条件下では依然として同一 crate 内のローカルな ThinLTO を許可し、off とは異なります。Profiles
別の最適化セットを比較したい場合は、独立した profile を作成した方が再現性が高くなります。
[profile.release-lto]
inherits = "release"
lto = "thin"
codegen-units = 1
debug = 1
cargo build --profile release-lto を実行します。codegen-units を減らすか LTO を有効にすると、最適化の機会が増える可能性がありますが、時間とメモリが増加する可能性もあり、必ずしも最小かつ最速の成果物が得られるわけではありません。s/z によるサイズ最適化も測定する必要があり、opt-level=3 を最小サイズオプションとして見なすべきではありません。
panic="abort" は例外処理のセマンティクスを変更し、catch_unwind はこのような panic をキャッチできなくなります。これはサイズのみに影響する無害なスイッチではありません。debug-assertions や overflow-checks もチェックの動作に影響を与えるため、ユーザーはテスト用とリリース用の設定の違いを把握しておく必要があります。
build.rs はビルド入力から出力を生成するプログラムです
スクリプトはホスト上で実行されますが、コンパイルターゲットは別のプラットフォームである可能性があります。ターゲットを照会する場合は TARGET または CARGO_CFG_* を読み取り、build.rs 内で cfg!(target_os=...) を使用してクロスコンパイルターゲットを判断しないでください。そうすると、スクリプト自身のホスト設定を見てしまうことになります。
出力ファイルは OUT_DIR に配置し、依存するファイルや環境を rerun-if-changed、rerun-if-env-changed を通じて宣言します。OUT_DIR は再ビルドの間、保持される可能性があるため、スクリプトは毎回空のディレクトリであると仮定すべきではありません。スクリプト自体やビルド依存関係の変更も再ビルドをトリガーするため、rerun 指示を1行出力するだけでは、トリガー条件は1つだけではありません。Build Scripts
C のコンパイルやバインディング生成の完全な例は bindgen を参照してください。build.rs は、依存関係グラフがすでに解決された後、rustc-cfg を通じて自分自身に新たな Cargo 依存関係を後から追加することはできません。カスタム cfg と Cargo feature は別のメカニズムです。
再生成結果を確認できる build.rs の例
前述の feature-demo プロジェクトのルートに label.txt を追加し、内容は service-a とします。次に、以下の build.rs を追加します。Cargo はこのデフォルトファイル名を自動的に認識します。スクリプトは設定を読み取り、それを Rust の文字列リテラルとしてエンコードして OUT_DIR に書き込みます。
use std:: { env, fs, path:: PathBuf} ;
fn main ( ) {
println! ( " cargo::rerun-if-changed=label.txt" ) ;
let label = fs:: read_to_string( " label.txt" ) .expect ( " read label.txt" ) ;
let output = PathBuf:: from( env:: var_os( " OUT_DIR" ) .expect ( " OUT_DIR" ) ) ;
fs:: write( output.join ( " build_info.rs" ) ,
format! ( " pub const LABEL: &str = {:?} ;\n " , label.trim ( ) ) )
.expect ( " write build_info.rs" ) ;
}
このステップで src/main.rs を以下に置き換えます。
include! ( concat! ( env! ( " OUT_DIR" ) , " /build_info.rs" ) ) ;
fn main ( ) {
assert! ( ! LABEL .is_empty ( ) ) ;
println! ( " {LABEL} " ) ;
}
最初の cargo run で service-a が出力されます。label.txt を service-b に変更して再度実行すると、再生成されて service-b が出力されるはずです。ここで {:?} は、文字列を引用符と必要なエスケープを含む Rust リテラルにエンコードするために使用されます。エスケープされていない外部テキストを直接ソースコードに連結してはいけません。trim はこのサンプルの設定戦略であり、先頭と末尾の空白を削除します。ラベルにこれらの文字が含まれる可能性がある場合は、別の解析方法を採用すべきです。
rerun-if-changed は、そのファイルの変更時にスクリプトを再実行する必要があることを宣言し、OUT_DIR は現在のビルドインスタンスの生成ディレクトリを提供します。他のワークスペースメンバー内で target/debug/build 下のハッシュ化されたディレクトリ名を手動で連結しないでください。ターゲット、profile、または feature コンテキストの変化により、このようなパスの仮定は脆くなります。
この例では、label を Cargo feature として扱わず、依存関係グラフも変更しません。入力が欠落している場合、expect によりビルドは失敗し、デフォルトの内容を黙って生成することはありません。実際のツールでは、必要に応じてより有用なビルド診断を出力できます。
設定が意図した通りに機能しているか確認する
cargo metadata はパッケージとターゲットを表示し、cargo tree -e features は feature の由来を説明し、cargo tree -d は重複するバージョンの特定を支援します。cargo build --locked はロックファイルの変更を必要とする解決変更を拒否しますが、ネットワークへのアクセスを禁止するものではありません。--offline はネットワークアクセスを制限しますが、ローカルインデックスやキャッシュが不足している場合に失敗する可能性があります。
再現可能な環境が必要な場合は、rust-toolchain、ターゲット、ネイティブ依存関係、およびビルドスクリプトの外部入力を記録する必要があります。crate のバージョンをロックすることはその一部に過ぎません。
「ロック、オフライン、再現性」を分離して検証する
オプション 制約 一般的な失敗の説明
--locked ロックファイルの変更を許可しない マニフェストと既存の解決結果が不一致、または必要な lock がまだ存在しない
--offline ネットワークへのアクセスなし ローカルインデックスまたはソースキャッシュが不足している、またはオプションのバージョンセットが変更される可能性あり
--frozen locked と offline の両方を要求 lock の再解決と書き込みができず、依存関係の取得もできない
同じ lock と同じソースコードがあっても、バイトレベルで同一の成果物が得られるとは限りません。ツールチェーン、ネイティブコンパイラ、ターゲット設定、環境パス、およびビルドスクリプトの入力はすべて出力に影響を与える可能性があります。再現性のあるビルドを追求する場合は、依存関係バージョン、テスト結果、プログラムの動作、または最終成果物のハッシュのいずれを比較対象とするかを明確にする必要があります。
最小ビルドマトリックスを使用して隠れた問題を発見する
前述の feature-demo に対しては、少なくともデフォルト/デフォルトなし、および json feature を個別に確認する必要があります。公開ライブラリの場合、宣言された最小 Rust バージョン、サポートされるターゲット、および必要な開発用ターゲットも確認すべきです。最新ツールチェーンでのみ1回ビルドしただけでは、rust-version 宣言が成立することを証明できません。
cargo check は通常、タイプエラーや設定エラーを迅速に見つけるのに十分ですが、最終的なリンクや実行を代替するものではありません。ネイティブライブラリ、エクスポートされたシンボル、またはランタイム初期化の問題は、より遅い段階で現れる可能性があります。変更内容に応じて検証フェーズを選択し、「マニフェストが解決できる」ことを「すべての構成で配信可能」と見なさないでください。