Rust structs, sometimes called structures, resemble struct types in C and C++, classes in Python, and objects in JavaScript.
A struct assembles several values of assorted types together into a single value so you can deal with them as a unit. Given a struct, you can read and modify its individual components. And a struct can have methods associated with it that operate on its components.
→ struct는 다양한 타입의, 여러 value들을 하나의 value로 조합해서, 하나의 단위로 다룰 수 있게 함!
→ struct가 주어지면, individual components를 읽고, 수정할 수 O
Rust has three kinds of struct types, named-field, tuple-like, and unit-like, which differ in how you refer to their components: a named-field struct gives a name to each component, whereas a tuple-like struct identifies them by the order in which they appear. Unit-like structs have no components at all; these are not common, but more useful than you might think.
The definition of a named0field struct type looks like this:
/// A rectangle of eight-bit grayscale pixels.
struct GrayscaleMap {
pixels: Vec<u8>,
size: (usize, usize)
}
This declares a type GrayscaleMap with two fields named pixels and size, of the given types.
→ pixels와 size라는 이름을 가진 두 개의 field와 함께 GrayscaleMap이라는 type을 정의하고 있음.
The convention in Rust is for all types, structs included, to have names that capitalize the first letter of each word, like GrayscaleMap, a convention called CamelCase (or PascalCase). Fields and methods are lowercase, with words separated by underscores. This is called snake_case.
→ Rust의 관습에 따르면 모든 type들의 이름은 각 단어의 첫 번째 문자가 대문자여야 하고, Fields와 methods들의 이름은 모든 문자들이 소문자이며, 각 단어들은 underscore로 분리되어야 한다.
You can construct a value of this type with a struct expression, like this:
let width = 1024;
let height = 576;
let image = GrayscaleMap {
pixels: vec![0; width * height],
size: (width, height)
};
A struct expression starts with the type name (GrayscaleMap) and lists the name and value of each field using key:value syntax, all enclosed in curly braces.
There’s also shorthand for populating fields from local variables or arguments with the same name: