1 분 소요

개요

  • 필드 초기화 축약법(field init shorthand)
    • 변수명과 구조체의 필드명이 같을 경우 변수명만으로 초기화 가능
  • 구조체 갱신법(struct update syntax)
    • .. 구문을 사용하여 기존 구조체의 값으로 초기화
  • 튜플 구조체(tuple structs)
    • 필드의 타입만 정의하여 튜플과 유사한 구조를 갖는 구조체
  • 유사 유닛 구조체(unit-like structs)
    • 필드가 없이 정의하여 유닛 타입인 ()와 비슷하게 동작하는 구조체
  • 연관 함수 (associated functions)
    • self 파라미터를 갖지 않는 함수


예제

  • 코드

        #[derive(Debug)]
        struct Test {
            i: i32,
            s: String,
        }

        impl Test {
            fn print(&self, prefix: i32) {
                println!("{} : {}, {}", prefix, self.i, self.s);
            }

            fn get_i(&self) -> i32 {
                self.i
            }

            fn set_i(&mut self, i: i32) {
                self.i = i;
            }

            fn from(i: i32, s: String) -> Test {
                Test { i, s }
            }
        }

        fn main() {
            {
                let test = Test {
                    i: 1,
                    s: String::from("a"),
                };
                println!("1 : {}, {}", test.i, test.s);
            }

            {
                let mut test = Test::from(1, String::from("a"));

                test.print(2);
                test.set_i(3);
                println!("3 : {}", test.get_i());
            }

            // field init shorthand
            {
                let i = 1;
                let s = String::from("a");

                let test = Test { i, s };
                println!("4 : {:?}", test);
            }

            // struct update syntax
            {
                let test1 = Test {
                    i: 1,
                    s: String::from("a"),
                };

                let test2 = Test {
                    s: String::from("b"),
                    ..test1
                };
                println!("5 : {:?}", test1);
                println!("6 : {:#?}", test2);
            }

            // tuple structs
            {
                struct TS(i32, String);

                let ts = TS(1, String::from("a"));
                println!("7 : {}, {}", ts.0, ts.1);
            }

            // unit-like structs
            {
                struct ULS();

                let uls = ULS();
            }
        }
  • 실행 결과

        1 : 1, a
        2 : 1, a
        3 : 3
        4 : Test { i: 1, s: "a" }
        5 : Test { i: 1, s: "a" }
        6 : Test {
            i: 1,
            s: "b",
        }
        7 : 1, a