Tuple Structs
Part of the Logic & Flow section of Coddy's Rust journey — lesson 25 of 66.
While regular structs use named fields, Rust offers another type called tuple structs. These provide a more concise way to create custom types when you don't need to name each field individually.
A tuple struct combines the benefits of creating a new type with the simplicity of a tuple. You define it using the struct keyword followed by the type name and the field types in parentheses:
struct Color(i32, i32, i32);This creates a Color type that holds three i32 values, representing RGB color values. Unlike regular structs, you don't specify field names - you access the values by their position, just like with tuples.
To create an instance of a tuple struct, you provide values in parentheses:
let red = Color(255, 0, 0);You can access individual fields using dot notation with the field index: red.0 gives you the first value, red.1 the second, and so on.
Challenge
EasyYou will receive three inputs: a red value (as an integer), a green value (as an integer), and a blue value (as an integer). Define a Color tuple struct that holds three i32 values representing RGB color components. Create an instance of this tuple struct using the input values, then access and print each color component using index notation.
Requirements:
- Define a
Colortuple struct with threei32fields - Read the first input and convert it to
i32for the red value - Read the second input and convert it to
i32for the green value - Read the third input and convert it to
i32for the blue value - Create an instance of the
Colortuple struct with these values - Access each field using dot notation with indices (0, 1, 2) and print the color information in the exact format shown below
Input:
- First line: Red value as an integer (e.g.,
255) - Second line: Green value as an integer (e.g.,
128) - Third line: Blue value as an integer (e.g.,
0)
Output:
- First line:
Red: [red_value] - Second line:
Green: [green_value] - Third line:
Blue: [blue_value]
Cheat sheet
A tuple struct is a struct without named fields. It combines the benefits of creating a new type with the simplicity of a tuple.
Define a tuple struct using the struct keyword followed by the type name and field types in parentheses:
struct Color(i32, i32, i32);Create an instance by providing values in parentheses:
let red = Color(255, 0, 0);Access fields using dot notation with the field index:
red.0 // first value
red.1 // second value
red.2 // third valueTry it yourself
use std::io;
// TODO: Define your Color tuple struct here
fn main() {
// Read red value
let mut red_input = String::new();
io::stdin().read_line(&mut red_input).expect("Failed to read line");
let red: i32 = red_input.trim().parse().expect("Invalid input");
// Read green value
let mut green_input = String::new();
io::stdin().read_line(&mut green_input).expect("Failed to read line");
let green: i32 = green_input.trim().parse().expect("Invalid input");
// Read blue value
let mut blue_input = String::new();
io::stdin().read_line(&mut blue_input).expect("Failed to read line");
let blue: i32 = blue_input.trim().parse().expect("Invalid input");
// TODO: Create an instance of Color tuple struct using the input values
// TODO: Access and print each color component using index notation
// Format: Red: [value], Green: [value], Blue: [value]
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Advanced Control Flow
The 'match' ExpressionMatching Multiple ValuesMatching RangesThe 'if let' ExpressionLoops as ExpressionsRecap - Simple Command Parser4Grouping Data with Structs
What is a Struct?Structs OverviewAccessing Struct FieldsMutable StructsStructs as Function ParametersTuple StructsRecap - Create a Book Struct7Handling Errors with 'Result'
What is a 'Result'?Using 'match' with 'Result'is_ok() and is_err()Shortcuts: unwrap and expectThe Question Mark Operator '?'Parsing Strings to NumbersRecap - Safe Division Function10Closures & Anonymous Functions
What is a Closure?Defining a Simple ClosureClosures with ParametersCapturing the EnvironmentRecap - Simple Adder Closure2Introduction to Vectors
What is a Vector?Creating a VectorAdding Elements with pushAccessing Vector ElementsIterating Over a VectorMutable IterationRemoving ElementsRecap - Basic Score Tracker5Key-Value Pairs with Hash Maps
What is a Hash Map?Creating a Hash MapInserting Key-Value PairsAccessing ValuesIterating Over a Hash MapUpdating a ValueRemoving a PairRecap - Word Counter8Project: Simple Item Inventory
Project SetupAdding an ItemChecking StockSelling an ItemPutting it all together