Rust - Structure Flashcards

1
Q

Struct defines data as

A

Key - value pairs

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Sytax of declaring a struct

A

struct Name_of_structure{
field 1: data_type,
field2: data_type,
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How to init a structure

A

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);
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Pass the Employee struct to a function

A

fn display( emp:Employee) {
println!(“Name is :{} company is {} age is
{}”,emp.name,emp.company,emp.age);
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How to return struct from a function

A

fn who_is_elder (emp1:Employee,emp2:Employee)->Employee {
if emp1.age>emp2.age {
return emp1;
} else {
return emp2;
}
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Describe Methods in structure

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Give the syntax of method in structure

A

struct My_struct{}

impl My_struct{
// set method context
fn method_name(){
//define a method

}
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Give an example of a method in struct

A

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());
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Describe Static Method in Srtructure

A

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();
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q
A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly