官术网_书友最值得收藏!

Data structures

Creating a data structure is one of the ways to add a new data type to Rust. A data structure is a group of variables that have been attached to each other, resulting in a single new data type that means all of these, together.

A new structure is defined using the struct keyword:

pub struct Constrained {
pub min: i32,
pub max: i32,
current: i32,
}
Notice the commas after each contained variable is defined. It can be tempting to use semicolons there, but that would cause a compiler error. The final comma is optional, but recommended, because it means that the lines can be rearranged without having to pay attention to where a comma might be missing, among other reasons.

Here, we've defined a structure called Constrained, which is made up of three different 32-bit unsigned integer variables. The structure itself is public, meaning that it can be used outside of the module where it's defined.

The min and max contained variables are also public, but that means something slightly different. It means that anywhere we have a Constrained value, we can access the min and max contained values directly. The current value, on the other hand, is private, which means that it can be directly accessed only within the module where the structure is defined. We can define functions in that module with the express purpose of accessing the data contained in private structure members, but the members themselves are not part of the structure's public interface, even if the structure itself is public.

To access min and max, we can use the same . symbol that we've seen previously in a few places. So, if cons is a mutable Constrained value, then we can do things like this:

cons.min = 5;
主站蜘蛛池模板: 济宁市| 阳城县| 集贤县| 濉溪县| 石阡县| 桐梓县| 黎平县| 婺源县| 龙江县| 西乡县| 个旧市| 蒲江县| 夏津县| 黎城县| 万源市| 仙游县| 洪洞县| 屏东市| 永定县| 平谷区| 金堂县| 扶风县| 栖霞市| 时尚| 香格里拉县| 芜湖县| 安岳县| 鹿泉市| 五大连池市| 肃北| 霍邱县| 江山市| 龙门县| 句容市| 台山市| 古浪县| 香港| 三明市| 罗源县| 翁牛特旗| 汤阴县|