- Structs are similar to tuples in this regard. However, unlike tuples, you must define the data type of the item within the struct.
struct Course {
code:i32,
name:String,
level:String,
}
let mut course1 = Course {
name:String::from("Rust"),
level:String::from("beginner"),
code:130,
};
let course2 = Course {
name:String::from("Javascript"),
level:String::from("beginner"),
code:122,
};
//update
course1.name = "Java".to_string();
course1.code = 134;
-
The name of the struct should be in PascalCase, meaning, the first letter of each word in a compound word is capitalized.
-
If this case is not followed, a warning,
⚠️ , is generated by the compiler. -
The order in which you assign values to items does not matter.
-
A struct instance is immutable by default. Therefore it cannot be updated unless made mutable. However, the values can be accessed.
-
Pass Structs to a function
fn display_mycourse_info(c:Course) {
println!("Name:{}, Level:{} ,code: {}", c .name, c .level, c.code);
}
- return a struct from a function
fn return_rust_course_info(c1:Course, c2:Course)-> Course{
//impl
}
// citing to struct mentioned above `Course`
//impl construct to define struct methods
impl Course {
fn name_code(&self) -> String {
format!("{} {}", self.name, self.code)
}
}
impl Course {
// static method also called as related methods
fn my_static_method(n: String, l: String, c:i32) -> Course {
Course {
name: n,
level:l,
code:c
}
} // such methods can be accessed using `::` operator.
//display
fn display(&self){
println!("name :{} code:{} of type: {}", self.name, self.code, self.level );
}
}
//define a tuple struct
struct FruitQuantity(String, i32);
// main function
fn main() {
// create an instance
let r1 = FruitQuantity("oranges".to_string(), 12);
}
#[derive(Debug)] // prints the value of struct using the debug trait
struct Point {
x: i32,
y: i32
}