Last active
January 8, 2017 10:45
-
-
Save dumindu/da4c10fd7e0b6d98a07ccaaaf5212a2d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Struct Declaration | |
struct Color { | |
red: u8, | |
green: u8, | |
blue: u8 | |
} | |
fn main() { | |
// creating an instance | |
let black = Color {red: 0, green: 0, blue: 0}; | |
// accessing it's fields, using dot notation | |
println!("Black = rgb({}, {}, {})", black.red, black.green, black.blue); //Black = rgb(0, 0, 0) | |
// structs are immutable by default, use `mut` to make it mutable but doesn't support field level mutability | |
let mut link_color = Color {red: 0,green: 0,blue: 255}; | |
link_color.blue = 238; | |
println!("Link Color = rgb({}, {}, {})", link_color.red, link_color.green, link_color.blue); //Link Color = rgb(0, 0, 238) | |
// copy elements from another instance | |
let blue = Color {blue: 255, .. link_color}; | |
println!("Blue = rgb({}, {}, {})", blue.red, blue.green, blue.blue); //Blue = rgb(0, 0, 255) | |
// destructure the instance using a `let` binding, this will not destruct blue instance | |
let Color {red: r, green: g, blue: b} = blue; | |
println!("Blue = rgb({}, {}, {})", r, g, b); //Blue = rgb(0, 0, 255) | |
// creating an instance via functions & accessing it's fields | |
let midnightblue = get_midnightblue_color(); | |
println!("Midnight Blue = rgb({}, {}, {})", midnightblue.red, midnightblue.green, midnightblue.blue); //Midnight Blue = rgb(25, 25, 112) | |
// destructure the instance using a `let` binding | |
let Color {red: r, green: g, blue: b} = get_midnightblue_color(); | |
println!("Midnight Blue = rgb({}, {}, {})", r, g, b); //Midnight Blue = rgb(25, 25, 112) | |
} | |
fn get_midnightblue_color() -> Color { | |
Color {red: 25, green: 25, blue: 112} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment