Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a field to an empty struct

Assuming I have a struct S of size 0x1 with the fields a and b, what is the most elegant way to add a field c to it?

Usually I am able to do it like this:

S = struct('a',0,'b',0); %1x1 struct with fields a,b
S.c = 0

However, if I receive an empty struct this does not work anymore:

S = struct('a',0,'b',0);
S(1) = []; % 0x1 struct with fields a,b
S.c = 0;
% A dot name structure assignment is illegal when the structure is empty.  
% Use a subscript on the structure.

I have thought of two ways to deal with this, but both are quite ugly and feel like workarounds rather than solutions. (Note the possibility of a non-empty struct should also be dealt with properly).

  1. Adding something to the struct to ensure it is not empty, adding the field, and making the struct empty again
  2. Initializing a new struct with the required fieldnames, filling it with the data from the original struct, and overwriting the original struct

I realize that it may be odd that I care about empty structs, but unfortunately part of the code that is not managed by me will crash if the fieldname does not exist. I have looked at help struct, help subsasgn and also searched for the given error message but so far I have not yet found any hints. Help is therefore much appreciated!

like image 510
Dennis Jaheruddin Avatar asked Feb 12 '13 10:02

Dennis Jaheruddin


People also ask

Can you have an empty struct?

An empty structIt occupies zero bytes of storage. As the empty struct consumes zero bytes, it follows that it needs no padding. Thus a struct comprised of empty structs also consumes no storage.

How do you know if a struct field is empty?

Checking for an empty struct in Go is straightforward in most cases. All you need to do is compare the struct to its zero value composite literal. This method works for structs where all fields are comparable.

Can you have an empty struct in C?

In this article we are going to learn about size of structure with no members (or Empty Structure) in C language with an example. Yes, it is allowed in C programming language that we can declare a structure without any member and in that case the size of the structure with no members will be 0 (Zero).

Can a field in a struct be an array?

The names and number of fields within the STRUCT are fixed. Each field can be a different type. A field within a STRUCT can also be another STRUCT , or an ARRAY or a MAP , allowing you to create nested data structures with a maximum nesting depth of 100.


1 Answers

You can use deal to solve this problem:

S = struct('a',0,'b',0);
S(1) = [];

[S(:).c] = deal(0);

This results in

S = 

1x0 struct array with fields:
    a
    b
    c 

This works also for non-empty structs:

S = struct('a',0,'b',0);

[S(:).c] = deal(0);

which results in

S = 

    a: 0
    b: 0
    c: 0
like image 144
H.Muster Avatar answered Sep 28 '22 23:09

H.Muster