Rust
RUST Documentation 따라 공부하기 9
2019.12.30
Structs
A struct or structure is a custom data type that lets you name and package together multiple related values that make up a meaningful group.
How to define
struct User {
  username: String,
  email: String,
  sign_in_count: u64,
  active: bool,
}
let user1 = User {
  email: String::from("some@email.com"),
  username: String::from("someuser"),
  active: true,
  sign_in_count: 1,
};
// if mutable,
let mut user1 = User {
  email: String::from("some@email.com"),
  username: String::from("someuser"),
  active: true,
  sign_in_count: 1,
};
user1.email = String::from("another@email.com");
Rust doesn't allow us to mark only certain fields as mutable. (The entire instance must be mutable.)
fn build_user(email: String, username: String) -> User {
  User {
    email: email,
    username: username,
    active: true,
    sign_in_count: 1,
  }
}
fn build_user_shorthand(email: String, username: String) -> User {
  User {
    email, // same name in struct
    username,
    active: true,
    sign_in_count: 1,
  }
}
Creating Instances From Other Instances With Struct Update Syntax
let user2 = User {
  email: String::from("another@email.com"),
  usename: String::from("user2"),
  ..user1
};
Creates an instance in
user2that has a different value forusernamebut has the same values for theactiveandsign_in_countfileds fromuser1.
Using Tuple Structs without Named Fields to Create Different Types
struct Color(i32, i32, i32);
struct Point(i32, i32, i32);
let black = Color(0,0,0);
let origin = Point(0,0,0);
Unit-Like Structs Without Any Fields
can also define structs that don't have any fields.
() : canbe useful in situations in which you need to implement a trait on some type but don't have any data that you want to store in the type itself.
