走进 Rust:结构体方法
Rust 大约 1117 字方法语法
方法与函数相似:它们使用fn
关键字及其名称进行声明,可以具有参数和返回值,并且包含一些在其他地方调用时运行的代码。但是,方法与函数的不同之处在于,它们是在结构体的上下文中定义的(或者是在enum
或trait
对象,分别在第6和17章中介绍),并且它们的第一个参数始终是self
,它代表调用该方法的结构体实例。
定义方法
impl
实现结构体,定义方法,方法的入参第一个参数必须是self
(一般传递实例的引用&self
,不然会被所有权drop
导致后续代码无法使用该实例)。
#[derive(Debug)]
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
fn area(&self) -> u32 {
self.width * self.height
}
}
fn main() {
let rect1 = Rectangle { width: 30, height: 50 };
println!(
"The area of the rectangle is {} square pixels.",
rect1.area()
);
}
相关函数
impl
实现结构体中,如果该函数的入参没有该结构体的实例,则该函数不能称为方法。一般这样的函数是用来初始化该结构体的实例。如String::from
。
impl Rectangle {
fn square(size: u32) -> Rectangle {
Rectangle { width: size, height: size }
}
}
多个impl块
impl
可以用来实现多次结构体,但定义的方法或函数不能同名,否则编译器会报duplicate definitions with name ...
错误。
impl Rectangle {
fn area(&self) -> u32 {
self.width * self.height
}
}
impl Rectangle {
fn can_hold(&self, other: &Rectangle) -> bool {
self.width > other.width && self.height > other.height
}
}
阅读 1845 · 发布于 2020-07-10
————        END        ————
Give me a Star, Thanks:)
https://github.com/fendoudebb扫描下方二维码关注公众号和小程序↓↓↓

昵称:
随便看看
换一批
-
单例双重校验为什么还要加 volatile阅读 734
-
Linux 两个文件取并集、交集、差集阅读 4407
-
Linux xxx is not in the sudoers file.This incident will be reported阅读 2534
-
面试题:OSI 模型和 TCP/I P模型各有几层阅读 3490
-
Linux zgrep,zcat,zless,zmore 等 zutil 包命令阅读 3863
-
设计模式之装饰者模式阅读 1951
-
OpenLDAP 简介阅读 56
-
GoJS 浏览器窗口缩放后自动居中对齐阅读 1982
-
Jedis OOM command not allowed when used memory > 'maxmemory'阅读 3281
-
Nginx 配置之图片防盗链阅读 2047