match 활용!
fn match_colours(rgb: (u32, u32, u32)){
match rgb{
(r, _, _) if r < 10 => println!("Not much red!"),
(_, g, _) if g < 10 => println!("Not much green!"),
(_, _, b) if b < 10 => println!("Not much blue!"),
_ => println!("Every colour has at least 10!")
}
}
fn main(){
let first = (200, 0, 0);
let second = (50, 50, 50);
let third = (200, 50, 0);
match_colours(first);
match_colours(second);
match_colours(third);
}
다음과 같이 여러 type을 혼용해서 사용할 수 없음
fn main(){
let my_number = 10;
let some_var = match my_number {
10 => 8,
_ => "Not ten"
};
}
if 를 사용해도 안되는건 마찬가지
fn main(){
let my_number = 8;
let some_var = if my_number == 10 {8} else {
"something else"
};
}
return 하는 값의 type을 맞추면 가능!
fn main(){
let my_number = 10;
let some_var = if my_number == 10 {"ten"} else {
"else"
};
println!("{}", some_var);
}
다음과 같이도 사용 가능
fn match_number(input: i32){
match input{
number @ 0..=10 => println!("It's between 0 and 10. Number : {}", number),
_ => println!("It's greater than ten")
}
}
fn main(){
match_number(10);
match_number(50);
}
Struct!
(나중에 비슷한 enum 도 있음)
rust에는 3가지 struct가 있음
// unit struct ( 아무것도 없는 구조체 )
struct FileDirectory;
fn main(){
let x = FileDirectory;
println!("The size of struct is {}", std::mem::size_of_val(&x)); // size : 0
}
// tuple struct
struct Colour(u8, u8, u8);
fn main(){
let my_colour = Colour(20, 50, 100);
println!("The second colour is {}", my_colour.1);
}
// named struct : 제일 많이 사용됨
struct Country{
population: u32,
capital : String,
leader_name : String
}
fn main(){
let canada = Country{
population : 35_000_000,
capital: "Ottawa".to_string(),
leader_name: "Justin Trudeau".to_string()
};
println!("The population is {}", canada.population);
}
Struct Size
struct Country {
population: u32,
capital: String,
leader_name: String
}
fn main(){
let population = 35_000_000;
let capital = "Ottawa".to_string();
let leader_name = "Justin Trudeau".to_string();
let my_country = Country {
population,
capital,
leader_name
};
}
-> js와 비슷한 기능!
use std::mem::size_of_val 을 사용해서 struct의 사이즈를 볼 수 있음
use std::mem::size_of_val;
struct Country {
population: u32,
capital: String,
leader_name: String
}
fn main(){
let population = 35_000_000;
let capital = "Ottawa".to_string();
let leader_name = "Justin Trudeau".to_string();
let my_country = Country {
population,
capital,
leader_name
};
println!("Country is {} bytes in size", size_of_val(&my_country));
}
Alignment
use std::mem::size_of_val;
struct Numbers{
one: u8,
two: u8,
three: u8
}
fn main(){
let my_numbers = Numbers{
one : 1,
two : 2,
three : 3
};
println!("Size of struct : {}", size_of_val(&my_numbers));
} // -> size : 3 (bytes)
use std::mem::size_of_val;
struct Numbers{
one: u8,
two: u8,
three: u8,
four: u32
}
fn main(){
let my_numbers = Numbers{
one : 1,
two : 2,
three : 3,
four: 4
};
println!("Size of struct : {}", size_of_val(&my_numbers));
} // -> size : 8 (bytes)
왜 size 가 7 이 아닌 8이냐면 러스트가 바이트수를 맞추기 위해........align하는...부분..
ENUM
struct 는 and 의 성격
enum 은 or 의 성격
enum ThingsInTheSky{
Sun, // compiler 가 보기에 0
Stars // compiler 가 보기에 1
}
fn create_sky_state(time: i32) -> ThingsInTheSky{
match time{
6..=18 => ThingsInTheSky::Sun,
_ => ThingsInTheSky::Stars
}
}
fn check_sky_state(state: &ThingsInTheSky){
match state{
ThingsInTheSky::Sun => println!("I can see the sun"),
ThingsInTheSky::Stars => println!("I can see the stars"),
}
}
fn main(){
let time = 8;
let sky_state = create_sky_state(time);
check_sky_state(&sky_state);
}
ENUM2 : 간편하게 사용하기
enum Mood{
Happy,
Sleepy,
NotBad,
Angry
}
fn match_mood(mood: &Mood) -> i32{
let happiness_level = match mood {
Mood::Happy => 10,
Mood::Sleepy => 6,
Mood::NotBad => 7,
Mood::Angry => 2
};
happiness_level
}
fn main(){
let my_mood = Mood::NotBad;
let happiness_level = match_mood(&my_mood);
println!("Out of 1 to 10, my happiness is {}", happiness_level);
}
이거를 use를 사용해서 쉽게 쓸 수 있음
enum Mood{
Happy,
Sleepy,
NotBad,
Angry
}
fn match_mood(mood: &Mood) -> i32{
use Mood::*;
let happiness_level = match mood {
Happy => 10, // Mood:: 안써도 됨
Sleepy => 6, // Mood:: 안써도 됨
NotBad => 7, // Mood:: 안써도 됨
Angry => 2 // Mood:: 안써도 됨
};
happiness_level
}
fn main(){
let my_mood = Mood::NotBad;
let happiness_level = match_mood(&my_mood);
println!("Out of 1 to 10, my happiness is {}", happiness_level);
}
enum의 인덱스(?)를 보려면
enum Season{
Spring, // 0
Summer, // 1
Autumn, // 2
Winter //3
}
fn main(){
use Season::*;
let four_seasons = vec![Spring, Summer, Autumn, Winter]; // Vec<Season>
for season in four_seasons {
println!("The number is: {}", season as u32);
}
}
ENUM3
enum Star{
BrownDwarf = 10,
RedDwarf = 50,
YellowStar = 100,
RedGiant = 1000,
DeadStar
}
fn main(){
use Star::*;
let starvec = vec![BrownDwarf, RedDwarf, YellowStar, RedGiant, DeadStar];
for star in starvec{
match star as u32{
size if size <= 80 => println!("Not the biggest star: {}", size),
size if size >= 80 => println!("Pretty big star: {}", size),
_ => println!("Some other star")
}
};
println!("What about DeadStar? It is: {}", DeadStar as u32); // 제일 마지막 숫자 + 1
}
enum 이 값을 가지게 할수있음
enum Number{
U32(u32),
I32(i32)
}
fn get_number(input: i32) -> Number {
let number = match input.is_positive(){
true => Number::U32(input as u32),
false => Number::I32(input)
};
number
}
fn main(){
let my_vec = vec![get_number(-800), get_number(8)];
for item in my_vec{
match item {
Number::U32(number) => println!("It's a u32 with the value : {}", number),
Number::I32(number) => println!("It's a i32 with the value : {}", number),
}
}
}
Loops
기본적인 loop
// rust 스럽지 않은 방법!
fn main(){
let mut counter = 0;
loop{
counter += 1;
println!("The counter is: {}", counter);
if counter == 5 {
break;
}
}
}
loop에 이름을 지을 수 있음! (tick 이라고 함)
fn main(){
let mut counter = 0;
let mut counter2 = 0;
'first_loop: loop {
counter += 1;
println!("The counter is now: {}", counter);
if counter > 9 {
println!("Now entering the second loop");
'second_loop: loop{
println!("The second counter is: {}", counter2);
counter2 += 1;
if counter2 == 3 {
break 'first_loop;
}
}
}
}
}
counter.. 만들어서 하면 rust 적이지 않은 loop!
그럼 어케?
fn main(){
let mut counter = 0;
while counter != 5 {
counter += 1;
println!("The counter is now: {}", counter);
}
}
while loop 도 괜찮긴 하지만 제일 많이 사용하는건 for loop
fn main(){
for number in 0..3 { // 0..3 -> exclusive range!
println!("The number is {}", number);
}
for number in 0..=3 { // 0..3 -> inclusive range!
println!("The number is {}", number);
}
}