Struct in carbon language is a composite type whose members are accessed through name and not by their positions. They are also known as structural data classes or struct types or struct.
Properties of Struct
Few properties of carbon struct are –
- Both struct types and values are written inside curly braces ({…}).
- In both cases, they have a comma-separated list of members that start with a period (
.
) followed by the field name. - In a struct type, the field name is followed by a colon (
:
) and the type, as in:{.name: String, .count: i32}
. - In a struct value, the field name is followed by an equal sign (
=
) and the value, as in{.key = "Joe", .count = 3}
.
Where Struct type can be used?
Struct type can be used as-
- The return type of a function that returns multiple values and wants those values to have names so a tuple is inappropriate
- An initializer for other
class
variables or values - A type parameter to a container
Code Example
var coordinates: {.x: i32, .y: i32} = {.y = 2, .x = 3}; var xCoordinate = coordinates.x; var yCoordinate = coordinates.y;
Here we are setting a variable to be of type struct. You can see that the sequence of value assignment doesn’t matter.
Conclusion
In this article we learned about Struct type in Carbon language. It’s a composite type where values can be accessed by their names. Unlike tuples, struct are more open to customization. They are maintainable and clean.
Carbon Language Series
- Introduction to Carbon Language.
- How to define variables in Carbon.
- Primitive Types – Bool, Int, Float, String
- Tuple in Carbon
- Struct in Carbon
- Pointers in Carbon
- Operators in Carbon Language
- Conditions & Control Flow in Carbon
- Ternary Operator (if expression) in Carbon
- Switch conditional in Carbon using Match
- Loops in Carbon
- Functions in Carbon