G2Labs Grzegorz Grzęda
Rust basic syntax
January 16, 2024
Start With Basic Syntax
Basic Structure of a Rust Program
Main Function: Like C, Rust programs start execution from a
main
function.Print to Console: Instead of C’s
printf
, Rust usesprintln!
for printing to the console. The!
signifies that it’s a macro, not a function.
Variables and Mutability
Immutable by Default: Unlike C, variables in Rust are immutable by default. To make a variable mutable, you use the
mut
keyword.Type Inference: Rust is strongly typed, but the compiler can often infer the type of the variable. You can also specify types explicitly.
1
let x: i32 = 5;
Data Types
Primitive Types: Rust has similar primitive types to C, like integers, floats, booleans, and characters. However, Rust’s types have a fixed size (
i32
,u64
, etc.).Tuples: Rust introduces tuples, which can hold a collection of values of different types.
1
let tup: (i32, f64, u8) = (500, 6.4, 1);
Arrays: Similar to C, but with a fixed size and all elements must be of the same type.
1
let a = [1, 2, 3, 4, 5];
Control Flow
If Statements: Similar to C but more strict in that the condition must be a boolean.
Loops: Rust offers several looping constructs, like
loop
,while
, andfor
. Thefor
loop, in particular, is more powerful and safer compared to C’s version.
Functions
Defining Functions: The syntax for defining functions is straightforward. Parameters need to have their types declared.
Function Calls: Function calling is similar to C.
1
let result = add(5, 6);
Comments
- Single Line and Multi-Line: Similar to C, Rust uses
//
for single-line comments and/* */
for multi-line comments.
Tips for C Developers Learning Rust Syntax
- Type System: Pay attention to Rust’s type system, which is more strict compared to C. Understanding this early will help prevent common bugs.
- Error Handling: Rust’s compiler errors are more informative than what you might be used to in C. Use them to guide your learning.
- Memory Safety: Rust ensures memory safety without a garbage collector. This might be a new concept if you’re coming from a manual memory management background.
- Ownership and Lifetimes: These are unique features of Rust not present in C. They might take time to grasp but are crucial for writing idiomatic Rust code.
Starting with these basic concepts and gradually experimenting with more complex features is a good approach to learning Rust. It’s important to write actual code and practice these concepts to get a good grasp of the language.