Rust - 結構體



陣列用於表示同構的值集合。類似地,結構體是 Rust 中另一種使用者定義的資料型別,它允許我們將不同型別的資料項組合在一起,包括另一個結構體。結構體將資料定義為鍵值對。

語法 - 宣告結構體

struct 關鍵字用於宣告結構體。由於結構體是靜態型別的,因此結構體中的每個欄位都必須與資料型別關聯。結構體的命名規則和約定與變數相同。結構體塊必須以分號結尾。

struct Name_of_structure {
   field1:data_type,
   field2:data_type,
   field3:data_type
}

語法 - 初始化結構體

宣告結構體後,應為每個欄位分配一個值。這稱為初始化。

let instance_name = Name_of_structure {
   field1:value1,
   field2:value2,
   field3:value3
}; 
//NOTE the semicolon
Syntax: Accessing values in a structure
Use the dot notation to access value of a specific field.
instance_name.field1
Illustration
struct Employee {
   name:String,
   company:String,
   age:u32
}
fn main() {
   let emp1 = Employee {
      company:String::from("TutorialsPoint"),
      name:String::from("Mohtashim"),
      age:50
   };
   println!("Name is :{} company is {} age is {}",emp1.name,emp1.company,emp1.age);
}

以上示例聲明瞭一個名為 Employee 的結構體,它包含三個欄位:name、company 和 age,它們的型別分別為。main() 函式初始化了該結構體。它使用 println! 宏列印結構體中定義的欄位的值。

輸出

Name is :Mohtashim company is TutorialsPoint age is 50

修改結構體例項

要修改例項,應將例項變數標記為可變的。以下示例宣告並初始化了一個名為 Employee 的結構體,然後將 age 欄位的值從 50 修改為 40。

let mut emp1 = Employee {
   company:String::from("TutorialsPoint"),
   name:String::from("Mohtashim"),
   age:50
};
emp1.age = 40;
println!("Name is :{} company is {} age is 
{}",emp1.name,emp1.company,emp1.age);

輸出

Name is :Mohtashim company is TutorialsPoint age is 40

將結構體傳遞給函式

以下示例演示瞭如何將結構體例項作為引數傳遞。display 方法以 Employee 例項作為引數,並列印其詳細資訊。

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

以下是完整的程式:

//declare a structure
struct Employee {
   name:String,
   company:String,
   age:u32
}
fn main() {
   //initialize a structure
   let emp1 = Employee {
      company:String::from("TutorialsPoint"),
      name:String::from("Mohtashim"),
      age:50
   };
   let emp2 = Employee{
      company:String::from("TutorialsPoint"),
      name:String::from("Kannan"),
      age:32
   };
   //pass emp1 and emp2 to display()
   display(emp1);
   display(emp2);
}
// fetch values of specific structure fields using the 
// operator and print it to the console
fn display( emp:Employee){
   println!("Name is :{} company is {} age is 
   {}",emp.name,emp.company,emp.age);
}

輸出

Name is :Mohtashim company is TutorialsPoint age is 50
Name is :Kannan company is TutorialsPoint age is 32

從函式返回結構體

讓我們考慮一個函式 who_is_elder(),它比較兩個員工的年齡並返回年齡較大的那個。

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

以下是完整的程式:

fn main() {
   //initialize structure
   let emp1 = Employee{
      company:String::from("TutorialsPoint"),
      name:String::from("Mohtashim"),
      age:50
   };
   let emp2 = Employee {
      company:String::from("TutorialsPoint"),
      name:String::from("Kannan"),
      age:32
   };
   let elder = who_is_elder(emp1,emp2);
   println!("elder is:");

   //prints details of the elder employee
   display(elder);
}
//accepts instances of employee structure and compares their age
fn who_is_elder (emp1:Employee,emp2:Employee)->Employee {
   if emp1.age>emp2.age {
      return emp1;
   } else {
      return emp2;
   }
}
//display name, comapny and age of the employee
fn display( emp:Employee) {
   println!("Name is :{} company is {} age is {}",emp.name,emp.company,emp.age);
}
//declare a structure
struct Employee {
   name:String,
   company:String,
   age:u32
}

輸出

elder is:
Name is :Mohtashim company is TutorialsPoint age is 50

結構體中的方法

方法類似於函式。它們是一組邏輯程式設計指令。方法使用 fn 關鍵字宣告。方法的作用域在結構體塊內。

方法是在結構體塊之外宣告的。impl 關鍵字用於在結構體的上下文中定義方法。方法的第一個引數始終為 self,它表示結構體的呼叫例項。方法對結構體的資料成員進行操作。

要呼叫方法,我們首先需要例項化結構體。可以使用結構體的例項呼叫該方法。

語法

struct My_struct {}
impl My_struct { 
   //set the method's context
   fn method_name() { 
      //define a method
   }
}

示例

以下示例定義了一個名為 Rectangle 的結構體,它包含 widthheight 兩個欄位。在結構體的上下文中定義了一個名為 area 的方法。area 方法透過 self 關鍵字訪問結構體的欄位並計算矩形的面積。

//define dimensions of a rectangle
struct Rectangle {
   width:u32, height:u32
}

//logic to calculate area of a rectangle
impl Rectangle {
   fn area(&self)->u32 {
      //use the . operator to fetch the value of a field via the self keyword
      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());
}

輸出

width is 10 height is 20 area of Rectangle is 200

結構體中的靜態方法

靜態方法可以用作實用程式方法。這些方法在結構體例項化之前就已經存在。靜態方法使用結構體的名稱呼叫,並且可以在沒有例項的情況下訪問。與普通方法不同,靜態方法不會接收 &self 引數。

語法 - 宣告靜態方法

靜態方法與函式和其他方法一樣,可以包含可選的引數。

impl Structure_Name {
   //static method that creates objects of the Point structure
   fn method_name(param1: datatype, param2: datatype) -> return_type {
      // logic goes here
   }
}

語法 - 呼叫靜態方法

structure_name :: 語法用於訪問靜態方法。

structure_name::method_name(v1,v2)

示例

以下示例使用 getInstance 方法作為工廠類,它建立並返回 Point 結構體的例項。

//declare a structure
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();
}

輸出

x =10 y=20
廣告

© . All rights reserved.