Rust datatypes: Difference between revisions
From wikinotes
(→string) |
(→char) |
||
Line 28: | Line 28: | ||
=== char === | === char === | ||
<blockquote> | <blockquote> | ||
chars refer to a single character, and use single-quotes. | |||
<syntaxhighlight lang="rust"> | <syntaxhighlight lang="rust"> | ||
char | let foo: char = 'a'; | ||
'a' | |||
</syntaxhighlight> | </syntaxhighlight> | ||
</blockquote><!-- char --> | </blockquote><!-- char --> |
Revision as of 23:51, 6 September 2021
Literals
'a' // char "abc" // string 1234 // i32 3.14 // f32 true/false // bool1_000 // == 1000 1.000_000 // == 1.000000
Primitives
Text
str
let foo: &str = "abcd";char
chars refer to a single character, and use single-quotes.
let foo: char = 'a';Numbers
implied type let var = 12;
assigned type let var: i8 = 12;
type suffix let var = 12i8;
Integers
- signed integers range is split in two, can be positive/negative
- unsigned integers are positive, and use all available bits
- use radix to calculate max size that can be accomodated with b bits
// signed integers, by bit-size i8 // -128..127 i16 // -32768..32767 i32 // -2147483648..2147483647 i64 // ... i128 isize // unsigned integers, by bit-size u8 // 0..255 u16 // 0..65535 u36 // 0..4294967295 u64 // ... u128 usizeFloating Point
f32 f64Boolean
true false
Collections
tuples
- tuples are dynamically sized
- tuples can store mixed types
- tuples can contain other tuples
var = (1, "two", 3.14) var.0 // item at index 1arrays
- arrays are homogenous
- arrays have a predeterminted/fixed size
- arrays are stored contiguously in memory
// initialization let var: [i32; 4] = [1, 2, 3, 4]; // declare an array of 4x 32-bit integers let var: [i32; 4] = [100; 4]; // initialize all 4x ints as 100 // methods var[0] // 1 var.len() // 4 // slices let foo = &var[1..2]; // [2, 3] println!("{}", foo[0]); // 2structs
struct Point { x: u8, y: u8 } // struct struct Unit // unit struct struct Color(i8, i8, i8); // tuple-structstruct
struct Point { x: u8, y: u8 }; let p: Point = Point { x: 5, y: 10 };unit struct
// an immutable trait-like object that stores no value. struct TestRuntuple struct
struct Color(i8, i8, i8); let c: Color = Color(100, 150, 200);
Other
Enums
enum TaskStatus { Blocked, Ready, Started, Finished, } TaskStatus::ReadyYou can also store complex information in a struct
enum Event { KeyPress(char), // like tuple-struct Click { x: i32, y: i32 }, // like c-structs Blue = 0x0000ff, // assign value } Event::KeyPress('j')Scoping with
use
use TaskStatus::*; let foo = Blocked; use TaskStatus::{Blocked, Ready}; let foo = Blocked; let bar = Started; // raises error, since not in scope