Rust learning: lessons, notes, and exercise crates
This commit is contained in:
@@ -0,0 +1 @@
|
||||
/target
|
||||
Generated
+7
@@ -0,0 +1,7 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "learn-struct"
|
||||
version = "0.1.0"
|
||||
@@ -0,0 +1,6 @@
|
||||
[package]
|
||||
name = "learn-struct"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
@@ -0,0 +1,81 @@
|
||||
struct User {
|
||||
active: bool,
|
||||
username: String,
|
||||
email: String,
|
||||
sign_in_count: usize,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Rectangle {
|
||||
width: u32,
|
||||
height: u32,
|
||||
}
|
||||
|
||||
impl Rectangle {
|
||||
fn area(&self) -> u32 {
|
||||
self.width * self.height
|
||||
}
|
||||
|
||||
fn width(&self) -> bool {
|
||||
self.width > 0
|
||||
}
|
||||
|
||||
fn square(size: u32) -> Self {
|
||||
Self {
|
||||
width: size,
|
||||
height: size,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
println!("Hello, world!");
|
||||
let mut user1 = User {
|
||||
active: true,
|
||||
username: String::from("username123"),
|
||||
email: String::from("user@ecample.com"),
|
||||
sign_in_count: 2,
|
||||
};
|
||||
|
||||
user1.username = String::from("kiki");
|
||||
|
||||
let user2 = build_user("email@asl.com", "kiki");
|
||||
|
||||
let _user3 = User {
|
||||
active: false,
|
||||
..user2
|
||||
};
|
||||
|
||||
// println!("{}", user2.username); //Error because the username is a String on heap and its already moved to the user3
|
||||
|
||||
let rect1 = Rectangle {
|
||||
width: 30,
|
||||
height: 20,
|
||||
};
|
||||
println!(
|
||||
"this is the area of the rect {} square pixels",
|
||||
rect1.area()
|
||||
);
|
||||
|
||||
println!("rect is {rect1:?}");
|
||||
|
||||
if rect1.width() {
|
||||
println!("The rectange have width")
|
||||
}
|
||||
|
||||
let rect2 = Rectangle::square(42);
|
||||
|
||||
println!(
|
||||
"this is the area of the rect2 {} square pixels",
|
||||
rect2.area()
|
||||
);
|
||||
}
|
||||
|
||||
fn build_user(email: &str, username: &str) -> User {
|
||||
User {
|
||||
active: true,
|
||||
username: String::from(username),
|
||||
email: String::from(email),
|
||||
sign_in_count: 2,
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user