Search code examples
javascripttypesgoogle-closure-compilergoogle-closure-library

What is the difference between struct and dict?


These two terms are used a lot in this documentation. The notion of struct is easy to understand i.e object whose properties are fixed but then we have dict which can have any number of properties so, how its different from the normal Object? why need a separate type for this feature?


Solution

  • I think the key difference is given on that documentation page

    By using @struct, you know that the compiler will rename all properties safely, because you can't use bracket access. By using @dict, you know that the properties will have the same name after compilation.

    (A key thing to understand about closure compiler is that properties accessed with bracket notation are not renamed).

    Using closure compiler restricts your usage of JavaScript, in the ways that YOU specify. You are telling the compiler to warn you when you write code that breaks the restrictions that you put in place with annotations like @struct and @dict.

    The @dict is indeed "like a normal Object" as you say. By using @dict you are telling the compiler that you are going to be adding properties to an object and you don't want those properties renamed to minimal names.

    In contrast @struct is typically used for class where you don't care what the compiler renames properties to be. You also don't expect to ever add a property to such an object, so it should be an error if you do.

    BTW, the examples on that page about struct and dict are a bit difficult to understand in my opinion, so if you are still confused about anything on that page feel free to ask more.