Why define a struct with single private field of unit type?

Stack Overflow Asked by m-bat on December 6, 2020

Why does ParseBoolError have the _priv field:

pub struct ParseBoolError {
    _priv: (),

I don’t think that the _priv field is used.

One Answer

You can't create an instance of a struct if it has private fields. This is just a trick to prevent ParseBoolError from being constructed in user code.

One reason to do this is for forwards compatibility. If users could create it with:

let error = ParseBoolError {};

then a future version of ParseBoolError couldn't add fields without breaking that code.

Correct answer by E_net4_is_being_impersonated on December 6, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP