러스트에선 let 이라는 키워드를 사용하여 변수를 선언한다.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fn main() { | |
let name = "레디"; | |
let fav_language : &str = "Rust"; | |
} |
기본적으로 타입 추론을 해주고, 타입을 명시할 수도 있다.
러스트는 상당히 많은 타입 종류를 가지고 있는데, 이건 다음번에 이야기 해보도록 하고 이 글에서 이야기 하고 싶은 것은 immutable과 mutable이다.
자바를 사용하면서 이런글까지 쓸 정도로 final을 숨 쉬듯 써왔다. 로컬 변수, 파라미터, 필드 등등 붙일 수 있는 변수들에는 전부 final을 붙여왔었는데, 붙이면서도 애매했던 점은 사실 final을 붙여도 불변은 아니라는 것이였다. 재할당은 막을 수 있지만, 그 값 안의 있는 값들이 변경되는 것은 막을 수 없었다.
뿐만 아니라 final을 붙여도 값이 추가되는 것을 막을 순 없다.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Main { | |
public static void main(final String[] args) { | |
final List<String> team = new ArrayList<>(); | |
team.add("레디"); | |
} | |
} |
위 코드는 문제없이 잘 돌아간다. (물론 List.of()로 생성하면 UnsupportedOperationException 에러가 발생하기는 하지만 그건 final을 붙이지 않아도 발생한다.)
하지만 러스트에선 immutable 한 녀석은 값이 추가되는 것을 허용하지 않는다.

mut을 붙여주면 야무지게 돌아가는 것을 확인 할 수 있다.

여기에서 러스트에게 한번 반했다.

'Programming Language > 러스트' 카테고리의 다른 글
[Rust] 러스트의 꽃, 소유권 (0) | 2024.11.22 |
---|---|
[Rust] 러스트에서 이분탐색 (0) | 2024.11.11 |