Struct Parameters

User-Defined Structs as Function Parameters

Structs pass and return by value, so one Book parameter replaces loose values and one return carries several results:

A Book struct in, a Sale struct outCSS
// out: 4 x f32
struct Book { price: f32, rating: f32, inStock: bool }
struct Sale { price: f32, featured: bool }
@group(0) @binding(0) var<storage, read_write> out: array<f32>;
fn onSale(book: Book, percentOff: f32) -> Sale {
  let price = round(book.price * (100 - percentOff)) / 100;
  return Sale(price, book.inStock && book.rating >= 4.5);
}
@compute @workgroup_size(1) fn main() {
  let a = onSale(Book(14.99, 4.6, true), 15);     // The Quiet Harbor
  let b = onSale(Book(24.00, 4.8, false), 15);    // Salt and Saffron, out of stock
  out[0] = a.price; out[1] = f32(a.featured); out[2] = b.price; out[3] = f32(b.featured);
}
Output
out: 12.739999771118164, 1, 20.399999618530273, 0

bool is fine here: these structs live in function memory, not a buffer (Arrays and Alignment).

A Book struct passed in and a Sale struct returned, driving two cover cards with prices and a featured badgeHTMLLive
<!doctype html>
<style>
  body { margin: 0; background: #f7f4ee; font: 14px system-ui, sans-serif; }
  .stage { position: relative; width: 100%; max-width: 600px; }
  .stage canvas { display: block; width: 100%; }
  .stage canvas + canvas { position: absolute; inset: 0; pointer-events: none; }
</style>
<div class="stage">
  <canvas id="view" width="600" height="320"></canvas>
  <canvas id="labels" width="600" height="320"></canvas>
</div>
<script>
const canvas = document.getElementById('view');
const ink = document.getElementById('labels').getContext('2d');

function showMessage(text) {                     // 2D fallback when WebGPU is missing
  const ctx = canvas.getContext('2d');
  ctx.fillStyle = '#fbeaea'; ctx.fillRect(0, 0, canvas.width, canvas.height);
  ctx.fillStyle = '#8a2b2b'; ctx.font = '18px system-ui, sans-serif'; ctx.textAlign = 'center';
  ctx.fillText(text, canvas.width / 2, canvas.height / 2);
}
function label(text, x, y, size = 12, color = '#2b2b2b', weight = '', align = 'left') {
  ink.font = `${weight} ${size}px system-ui, sans-serif`; ink.fillStyle = color; ink.textAlign = align; ink.fillText(text, x, y);
}

const lab = /* wgsl */ `
struct Book { price: f32, rating: f32, inStock: bool }
struct Sale { price: f32, featured: bool }
@group(0) @binding(0) var<storage, read_write> out: array<f32>;
fn onSale(book: Book, percentOff: f32) -> Sale {
  let price = round(book.price * (100 - percentOff)) / 100;
  return Sale(price, book.inStock && book.rating >= 4.5);
}
@compute @workgroup_size(1) fn main() {
  let a = onSale(Book(14.99, 4.6, true), 15);     // The Quiet Harbor
  let b = onSale(Book(24.00, 4.8, false), 15);    // Salt and Saffron, out of stock
  out[0] = a.price; out[1] = f32(a.featured); out[2] = b.price; out[3] = f32(b.featured);
}`;
// Two covers; a gold star appears only where the Sale said featured.
const view = /* wgsl */ `
@group(0) @binding(0) var<storage> out: array<f32>;
struct Out { @builtin(position) pos: vec4f, @location(0) uv: vec2f, @location(1) @interpolate(flat) card: u32 }
@vertex fn vs(@builtin(vertex_index) v: u32, @builtin(instance_index) i: u32) -> Out {
  let q = vec2f(f32(v & 1), f32(v >> 1));
  let px = vec2f(30 + f32(i) * 300 + q.x * 110, 40 + q.y * 220);
  return Out(vec4f(px.x / 300 - 1, 1 - px.y / 160, 0, 1), q, i);
}
fn star(p: vec2f) -> f32 {                                 // 1 inside a five-pointed star
  let a = atan2(p.y, p.x);
  let r = 0.55 + 0.45 * cos(5 * a) * 0.5 + 0.2;
  return step(length(p), r * 0.18);
}
@fragment fn fs(in: Out) -> @location(0) vec4f {
  let base = select(vec3f(0.08, 0.40, 0.75), vec3f(0.71, 0.27, 0.18), in.card == 1u);
  var color = base * (0.75 + 0.25 * smoothstep(0.0, 0.12, in.uv.x));        // spine shading
  color = mix(color, vec3f(0.98, 0.95, 0.86), step(0.55, in.uv.y) * step(in.uv.y, 0.6));
  let featured = out[in.card * 2 + 1] > 0.5;
  let s = star((in.uv - vec2f(0.8, 0.12)) * vec2f(1, 1.47)) * f32(featured);
  return vec4f(mix(color, vec3f(1.0, 0.80, 0.15), s), 1);
}`;

async function main() {
  const adapter = await navigator.gpu?.requestAdapter();
  if (!adapter) return showMessage('WebGPU is not available in this browser');
  const device = await adapter.requestDevice();
  const context = canvas.getContext('webgpu');
  const format = navigator.gpu.getPreferredCanvasFormat();
  context.configure({ device, format });
  const B = GPUBufferUsage;
  const out = device.createBuffer({ size: 16, usage: B.STORAGE | B.COPY_SRC });
  const read = device.createBuffer({ size: 16, usage: B.COPY_DST | B.MAP_READ });
  const compute = device.createComputePipeline({ layout: 'auto', compute: { module: device.createShaderModule({ code: lab }) } });
  const module = device.createShaderModule({ code: view });
  const render = device.createRenderPipeline({ layout: 'auto', primitive: { topology: 'triangle-strip' },
    vertex: { module }, fragment: { module, targets: [{ format }] } });

  const encoder = device.createCommandEncoder();
  const cp = encoder.beginComputePass();
  cp.setPipeline(compute);
  cp.setBindGroup(0, device.createBindGroup({ layout: compute.getBindGroupLayout(0), entries: [{ binding: 0, resource: { buffer: out } }] }));
  cp.dispatchWorkgroups(1);
  cp.end();
  const pass = encoder.beginRenderPass({ colorAttachments: [{ view: context.getCurrentTexture().createView(),
    clearValue: [0.97, 0.96, 0.93, 1], loadOp: 'clear', storeOp: 'store' }] });
  pass.setPipeline(render);
  pass.setBindGroup(0, device.createBindGroup({ layout: render.getBindGroupLayout(0), entries: [{ binding: 0, resource: { buffer: out } }] }));
  pass.draw(4, 2);
  pass.end();
  encoder.copyBufferToBuffer(out, 0, read, 0, 16);
  device.queue.submit([encoder.finish()]);
  await read.mapAsync(GPUMapMode.READ);
  const o = new Float32Array(read.getMappedRange().slice(0));
  read.unmap();

  const cards = [['The Quiet Harbor', 'Book(14.99, 4.6, true)', 14.99], ['Salt and Saffron', 'Book(24.00, 4.8, false)', 24.00]];
  cards.forEach(([title, literal, price], i) => {
    const x = 152 + i * 300;
    label(title, 85 + i * 300, 282, 13, '#222', 'bold', 'center');
    label(literal, x, 70, 11, '#444');
    label('onSale(book, 15) returns', x, 100, 11, '#444');
    label(`price $${o[i * 2].toFixed(2)}`, x, 126, 15, '#1e6b3a', 'bold');
    label(`was $${price.toFixed(2)}`, x, 146, 11, '#777');
    label(`featured: ${o[i * 2 + 1] > 0.5}`, x, 172, 13, o[i * 2 + 1] > 0.5 ? '#8a5a00' : '#777', 'bold');
  });
  label('bool members are fine here: these structs live in function memory, not in a buffer.', 20, 310, 12, '#444');
}
main();
</script>