The struct keyword represents composite data types in C, C++, and Rust. A struct is like a class only with attributes and no methods. We can use them to implement data structures in our programs.

Members of a struct can be accessed via two methods:

  • The dot operator is used when we don’t need to dereference (like when a structure hasn’t been dynamically allocated).
  • The arrow operator is used when dereferencing, i.e., the struct is a pointer.
pNeuron -> input = 7.94; // equivalent to
(*pNeuron).input = 7.94

Note that we can only compare struct field-by-field. Note that the equality operator in both languages produces a shallow copy.

Definition and initialisation

The struct definition does not involve the allocation of memory. Memory is only allocated when struct is instantiated through variable declaration or dynamic allocation.

struct Neuron {
	int neuronNum;
	double input1, input2;
	char areaName[20];
} // anytime we call this structure, we call it struct Neuron

We can also define an alias for a data structure so we can assign a name for an existing data type, either in the same statement or in a statement after the structure type is defined.

typedef struct neuron {
	int data;
} Neuron;

We can initialise a struct in a single statement:

struct spaceship ship = {
	.manufacturer = "NASA",
	.ci.window_count = 9,
	.ci.o2level = 21
};

In Rust

Note that to modify the struct’s values, the entire instance must be mutable, i.e., specific fields cannot be mutable and others immutable.

In assembly

The space requirements of struct tells the compiler how much memory to map out for each instance.