Skip to content

Rust Playgroundをブログで使う

This content is not available in your language yet.

こんな感じになります。

fn main() {
println!("Hello, Rust!");
}

上の実行ボタンを押すと、結果が出力されます。

対応方法

  1. playground.jsを作成

    次のplayground.jsを、publicディレクトリに作成します。

    • astro.config.mjs
    • Directorysrc/
    • Directorypublic/
      • playground.js
    playground.js
    // playground.js
    function setupRustPlaygrounds() {
    document.querySelectorAll('pre[data-language="rustpg"]').forEach((codeBlock) => {
    const pre = codeBlock.parentElement;
    const code = codeBlock.textContent;
    // ボタン作成
    const button = document.createElement('button');
    button.textContent = '▶ 実行';
    button.style.margin = '8px 0';
    button.style.padding = '4px 12px';
    button.style.backgroundColor = '#ea580c';
    button.style.color = 'white';
    button.style.border = 'none';
    button.style.borderRadius = '6px';
    button.style.cursor = 'pointer';
    // 出力表示用のプレ要素
    const output = document.createElement('pre');
    output.style.background = '#111';
    output.style.color = '#eee';
    output.style.padding = '1rem';
    output.style.borderRadius = '8px';
    output.style.marginTop = '0.5rem';
    output.textContent = '(ここに出力されます)';
    // 実行処理
    button.onclick = async () => {
    output.textContent = '実行中...';
    const response = await fetch('https://play.rust-lang.org/execute', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
    channel: 'stable',
    mode: 'debug',
    edition: '2021',
    crateType: 'bin',
    tests: false,
    code: code,
    }),
    });
    const result = await response.json();
    output.textContent = result.success
    ? result.stdout || '(出力なし)'
    : result.stderr || 'エラーが発生しました';
    };
    // 挿入
    pre.parentNode.insertBefore(button, pre.nextSibling);
    pre.parentNode.insertBefore(output, button.nextSibling);
    });
    }
    // ページロード後に処理
    window.addEventListener('DOMContentLoaded', setupRustPlaygrounds);
  2. playground.jsを読み込ませる

    astro.config.mjsに次のように追記します。 遅延読み込みさせるため、defer属性をつけます。

    export default defineConfig({
    integrations: [
    starlight({
    title: '*****',
    head: [
    {
    tag: 'script',
    attrs: {
    src: '/playground.js',
    type: 'text/javascript',
    defer: true,
    },
    },
    ],
    }),
    ],
    });