Learning Rust
November 29, 2024
rustI have been using Bash Shell scripts for many years, but wanted something to learn that would give me more power. I have looked at Golang, Typescript and Python but decided to give Rust a whirl.
The first reason was to be able to make powerful asynchronous commands to download and check websites, but I also wanted a language that offered more than php and bash shell scripting do.
As a PHP developer venturing into the world of Rust, understanding how familiar PHP types translate to Rust types is crucial. This guide will help you bridge the gap between these two languages, focusing on type conversions and key differences.
Basic Types
Integers
PHP's integer type can be represented by several Rust integer types, depending on the size and signedness:
PHP | Rust |
---|---|
int | i32, i64, u32, u64 |
In Rust, you need to be more specific about the integer size and whether it's signed or unsigned. For most cases, i32
(32-bit signed integer) is a good default choice.
Floating-Point Numbers
PHP's float type corresponds to Rust's f32 and f64:
PHP | Rust |
---|---|
float | f32, f64 |
f64
is typically used as the default float type in Rust, offering higher precision.
Booleans
Booleans are straightforward:
PHP | Rust |
---|---|
bool | bool |
Strings
PHP strings are more complex to translate due to Rust's distinction between string slices and owned strings:
PHP | Rust |
---|---|
string | String, &str |
In Rust, String
is the owned, growable string type, while &str
is a string slice (a reference to a string).
Compound Types
Arrays
PHP's arrays are versatile and can be translated to different Rust types depending on usage:
PHP | Rust |
---|---|
array (indexed) | Vec |
array (associative) | HashMap<K, V> |
Rust's Vec<T>
is similar to PHP's indexed arrays, while HashMap<K, V>
is more akin to associative arrays.
Objects
PHP's objects don't have a direct equivalent in Rust. Instead, you'll typically use structs and enums:
PHP | Rust |
---|---|
object | struct, enum |
Rust's structs and enums provide more control over data representation and behavior.
Special Types
Null
PHP's null doesn't exist in Rust. Instead, Rust uses the Option<T>
enum:
PHP | Rust |
---|---|
null | Option |
Option<T>
can be either Some(value)
or None
, providing a safer way to handle the absence of a value.
Resource
PHP's resource type doesn't have a direct equivalent in Rust. Instead, Rust uses specific types for handling resources, often wrapped in smart pointers or custom types.
Type Conversion
In Rust, type conversion is more explicit than in PHP. You can use the as
keyword for simple conversions, or implement the From
and Into
traits for more complex conversions[5].
let num: u8 = 10;
let float_num: f32 = num as f32;
If you would like to contact me with this form on londinium.com, ilminster.net or via Twitter @andylondon