Rust - Structure Flashcards
Struct defines data as
Key - value pairs
Sytax of declaring a struct
struct Name_of_structure{
field 1: data_type,
field2: data_type,
}
How to init a structure
struct Employee{
company: String,
name: String,
age: u32
}
fn main () {
let emp1 = Employee{
company: String::from(“sth”),
name: String:: from(“Prince”).
age: 19
};
println!(“Name is :{} company is {} age is {}”,emp1.name,emp1.company,emp1.age);
}
Pass the Employee struct to a function
fn display( emp:Employee) {
println!(“Name is :{} company is {} age is
{}”,emp.name,emp.company,emp.age);
}
How to return struct from a function
fn who_is_elder (emp1:Employee,emp2:Employee)->Employee {
if emp1.age>emp2.age {
return emp1;
} else {
return emp2;
}
}
Describe Methods in structure
Methods are declared outside the structure block.
The impl keyword is used to define a method within the context of a structure.
The first parameter of a method will be always self, which represents the calling instance of the structure.
Methods operate on the data members of a structure.
Give the syntax of method in structure
struct My_struct{}
impl My_struct{
// set method context
fn method_name(){
//define a method
}
}
Give an example of a method in struct
struct Rectangle{
width:u32,
height:u32
}
impl Rectange{
fn area(&self) -> u32{
self.width * self.height
}
}
fn main() {
// instanatiate the structure
let small = Rectangle {
width:10,
height:20
};
//print the rectangle’s area
println!(“width is {} height is {} area of Rectangle
is {}”,small.width,small.height,small.area());
}
Describe Static Method in Srtructure
struct Point {
x: i32,
y: i32,
}
impl Point {
//static method that creates objects of the Point structure
fn getInstance(x: i32, y: i32) -> Point {
Point { x: x, y: y }
}
//display values of the structure’s field
fn display(&self){
println!(“x ={} y={}”,self.x,self.y );
}
}
fn main(){
// Invoke the static method
let p1 = Point::getInstance(10,20);
p1.display();
}