Struct in Carbon Language – Composite Types

Total
0
Shares
struct in carbon language

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 –

  1. Both struct types and values are written inside curly braces ({…}).
  2. In both cases, they have a comma-separated list of members that start with a period (.) followed by the field name.
  3. In a struct type, the field name is followed by a colon (:) and the type, as in: {.name: String, .count: i32}.
  4. 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.

Sign Up for Our Newsletters

Get only the best articles delivered to your mail

You May Also Like
operators in carbon language

Operators in Carbon Language

Table of Contents Hide ArithmeticBitwise & BitshiftComparisonConversionLogicalIndexingFunction CallPointerMoveConclusion We have a number of operators in Carbon language like – Arithmetic, Bitwise, BitShift, Comparison, Conversion, Logical, Indexing, function call, pointer, move…
View Post
introduction to carbon language - what and why it is created

Introduction to Carbon Language

Table of Contents Hide IntroductionFeatures of Carbon LanguageWhy developed Carbon? Why not upgraded C++?Where Carbon could be used?Carbon is written in which language?Code Example Carbon Language is the successor to…
View Post