rust-lang/rust · error · B::Error

Cannot create a zero-sized constant for type

Error message

Cannot create a zero-sized constant for type `{ty_internal}`: {err}

What it means

Thrown by `try_new_const_zst` (impls.rs:475) when computing the layout of `ty_internal` fails. `layout_of` returns an error for types whose layout cannot be determined — unsized types, types with normalization errors, size overflow, or cyclic layout.

Solutions

  1. Resolve/normalize the type and confirm it is sized before constructing a ZST constant.
  2. If the type genuinely has no static layout, construct the constant through a different path (e.g. an explicit allocation).
  3. Catch the layout error and report the offending type for diagnosis.

Example fix

// before
let c = ctxt.try_new_const_zst(ty)?;

// after
// ensure the type has a computable layout first
let layout = ctxt.tcx.layout_of(ctxt.fully_monomorphized().as_query_input(ty))
    .map_err(|e| format!("layout error for {ty}: {e}"))?;
let c = ctxt.try_new_const_zst(ty)?;
Defensive patterns

Strategy: try-catch

Validate before calling

// Pre-check layout computability before constructing the ZST constant.
if ctxt.tcx.layout_of(ctxt.fully_monomorphized().as_query_input(ty)).is_err() {
    return Err(format!("type {ty} has no computable layout"));
}

Type guard

fn has_computable_layout<'tcx>(ty: Ty<'tcx>, tcx: TyCtxt<'tcx>, env: TypingEnv<'tcx>) -> bool {
    tcx.layout_of(env.as_query_input(ty)).is_ok()
}

Try / catch

let c = match ctxt.try_new_const_zst(ty) {
    Ok(c) => c,
    Err(e) => {
        // layout failed; log type and fall back or propagate
        return Err(e);
    }
};

Prevention

When it happens

Trigger: Calling `try_new_const_zst` on an unsized type (`str`, `dyn Trait`, slices), a type with an unknown/opaque layout, or a type whose layout computation overflows or hits a cycle.

Common situations: Constructing zero-sized constants from inferred or generic types whose layout is not yet resolvable; passing foreign-opaque types into const construction.

Related errors


AI-assisted analysis of rust-lang/rust@7088e4b63a (2026-08-10). Data as JSON: /api/errors/c710bb6f79261d19. Report an issue: GitHub.

Appendix: source

Thrown at compiler/rustc_public_bridge/src/context/impls.rs:475

    /// Evaluate constant as a target usize.
    pub fn eval_target_usize(&self, cnst: MirConst<'tcx>) -> Result<u64, B::Error> {
        use crate::context::TypingEnvHelpers;
        cnst.try_eval_target_usize(self.tcx, self.fully_monomorphized())
            .ok_or_else(|| B::Error::new(format!("Const `{cnst:?}` cannot be encoded as u64")))
    }

    pub fn eval_target_usize_ty(&self, cnst: ty::Const<'tcx>) -> Result<u64, B::Error> {
        cnst.try_to_target_usize(self.tcx)
            .ok_or_else(|| B::Error::new(format!("Const `{cnst:?}` cannot be encoded as u64")))
    }

    pub fn try_new_const_zst(&self, ty_internal: Ty<'tcx>) -> Result<MirConst<'tcx>, B::Error> {
        let size = self
            .tcx
            .layout_of(self.fully_monomorphized().as_query_input(ty_internal))
            .map_err(|err| {
                B::Error::new(format!(
                    "Cannot create a zero-sized constant for type `{ty_internal}`: {err}"
                ))
            })?
            .size;
        if size.bytes() != 0 {
            return Err(B::Error::new(format!(
                "Cannot create a zero-sized constant for type `{ty_internal}`: \
                Type `{ty_internal}` has {} bytes",
                size.bytes()
            )));
        }

        Ok(MirConst::Ty(ty_internal, self.const_zero_sized(ty_internal)))
    }

    pub fn const_zero_sized(&self, ty_internal: Ty<'tcx>) -> ty::Const<'tcx> {
        ty::Const::zero_sized(self.tcx, ty_internal)
    }

View on GitHub (pinned to 7088e4b63a)