Rust by Example | страница 12



>let ys: [i32; 500] = [0; 500];

>// Indexing starts at 0

>println!("first element of the array: {}", xs[0]);

>println!("second element of the array: {}", xs[1]);

>// `len` returns the count of elements in the array

>println!("number of elements in array: {}", xs.len());

>// Arrays are stack allocated

>println!("array occupies {} bytes", mem::size_of_val(&xs));

>// Arrays can be automatically borrowed as slices

>println!("borrow the whole array as a slice");

>analyze_slice(&xs);

>// Slices can point to a section of an array

>// They are of the form [starting_index..ending_index]

>// starting_index is the first position in the slice

>// ending_index is one more than the last position in the slice

>println!("borrow a section of the array as a slice");

>analyze_slice(&ys[1 .. 4]);

>// Out of bound indexing causes compile error

>println!("{}", xs[5]);

>}

>הההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההה

>XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Rust custom data types are formed mainly through the two keywords:

   • struct: define a structure

   • enum: define an enumeration

Constants can also be created via the const and static keywords.

There are three types of structures ("structs") that can be created using the struct keyword:

   • Tuple structs, which are, basically, named tuples.

   • The classic C structs

   • Unit structs, which are field-less, are useful for generics.

>#[derive(Debug)]

>struct Person {

>name: String,

>age: u8,

>}

>// A unit struct

>struct Unit;

>// A tuple struct

>struct Pair(i32, f32);

>// A struct with two fields

>struct Point {

>x: f32,

>y: f32,

>}

>// Structs can be reused as fields of another struct

>#[allow(dead_code)]

>struct Rectangle {

>// A rectangle can be specified by where the top left and bottom right

>// corners are in space.

>top_left: Point,

>bottom_right: Point,

>}

>fn main() {

>// Create struct with field init shorthand

>let name = String::from("Peter");

>let age = 27;

>let peter = Person { name, age };

>// Print debug struct

>println!("{:?}", peter);

>// Instantiate a `Point`

>let point: Point = Point { x: 10.3, y: 0.4 };