Download View/Open

Transcript
2.1. THE RUST PROGRAMMING LANGUAGE
17
Structs
A struct in Rust is similar to that of C and is a way of creating more advanced data
types than primitives or enums. With a struct, it is possible to combine multiple
variables into a single type, each of them identified by its name. An example of
defining a Book is shown in Listing 2.4. Anyone that is familiar with C will see
the similarity of the struct definition, but there is also a couple of extra things
to notice from the example. Everything in Rust is private by default, but the pub
keywords on type definitions and member fields make them publicly accessible. The
impl keyword allows us to implement member functions for the Book, similar to
class-declarations in C++ and other object-oriented languages.
1
2
3
4
pub struct Book {
pub name: String,
pub pages: u32,
}
5
6
7
8
9
10
impl Book {
pub fn info(&self) {
println!("{} has {} pages.", self.name, self.pages);
}
}
Listing 2.4: Struct definition and implementation
Pointers
Rust’s core library exposes two pointer types that are considered unsafe by the
language, which Section 2.1.7 explains. Pointers in Rust are a fundamental part of
the language, but they are not used much outside of low-level code and bindings.
Instead, the library offers higher-level structures as an abstraction between the raw
pointers and their data.
Slices
The Slice type is simply a view into an array, and it is represented by a pointer
and a length, as shown in Listing 2.5. Slices like the arrays comes with bounds
checking, although this can be circumvented for performance reasons. The length
is used to determine how many elements the slice represents. Note that the representation given here is internal to the compiler and the length property is not
directly accessible. Slice syntax is denoted by &[T], which reads like ‘a slice of a
finite array with type T.’