zoukankan      html  css  js  c++  java
  • 【转】rust中impl关键字的用法What is the Impl keyword in Rust?

    原文:https://www.educative.io/edpresso/what-is-the-impl-keyword-in-rust

    -----------------

    The impl keyword in Rust is used to implement some functionality on types. This functionality can include both functions and costs. There are two main kinds of implementations in Rust:

    1. Inherent implementations
    2. Trait implementations

    In this shot, we will focus on inherent implementations. You can learn more about trait implementations here.

    Inherent implementations, as the name implies, are standalone. They are tied to a single concrete self type that is specified after the impl keyword. These implementations, unlike standard functions, are always in scope.

    Code

    In the following program, we are adding methods to a Person struct with the impl keyword:

    struct Person {
      name: String,
      age: u32
    }
    
    // Implementing functionality on the Person struct with the impl keyword
    impl Person{
      // This method is used to introduce a person
      fn introduction(&self){
        println!("Hello! My name is {} and I am {} years old.", self.name, self.age);
      }
    
      // This method updates the age of the person on their birthday
      fn birthday(&mut self){
        self.age = self.age + 1
      }
    }
    
    fn main() {
      // Instantiating a mutable Person object
      let mut person = Person{name: "Hania".to_string(), age: 23};
      
      // person introduces themself before their birthday
      println!("Introduction before birthday:");
      person.introduction();
      
      // person ages one year on their birthday
      person.birthday();
      
      // person introduces themself after their birthday
      println!("\nIntroduction after birthday:");
      person.introduction();
    }
    

      

    CREATOR

    Anusheh Zohair Mustafeez
  • 相关阅读:
    Get IPv4 Address 2.0
    Apache Tomcat Manager 2.0
    Apache Tomcat Manager 1.0
    FTP自动登录脚本文件
    VMware Workstation 10 + CentOS-5.5-i386 + MySQL Server 5.5
    Copy Files Blurry 1.0
    Extract Chorus From Audio 1.0
    Refresh Baidu Zhidao Evaluate Num 2.0
    File Split 1.0
    其它有趣的事情分享
  • 原文地址:https://www.cnblogs.com/oxspirt/p/15600856.html
Copyright © 2011-2022 走看看