struct method#
Method 란?#
Method는 Struct 안에 포함되어 있는 것이 다를 뿐, Function과 같다고 볼 수 있습니다.
Method를 정의 하는 방법을 알아 봅시다.
다음 예제의 struct Person { ~~~ } 처럼 Person Struct를 정의 했습니다.impl Person 에서 impl은 implementation의 약어입니다.impl { ~~~ } 안에 만들어지는 Function이 Method입니다.fn speak(self) { ~~~ }처럼 Method를 만들었고, 첫번째 Parameter로 self를 전달 받았습니다.self는 자기 자신인 struct Person을 가르킵니다.
반드시 Method의 첫번째 Parameter로 self를 받아야 합니다. 그렇지 않으면 Compile error가 발생합니다.println!("hi, {}", self.name); 은 self.name을 print하고 있습니다.
여기서 self.name은 struct Person { name: String, } 안의 name: String을 가리키는 것입니다.let person = Person{ ~~~ }; 처럼 Instance를 생성 후, person.speak() 처럼 Method를 호출 할 수 있습니다.