You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

86 lines
2.3 KiB
Plaintext

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

// Functions
// `i32` is the type for 32-bit signed integers
fn add2(x: i32, y: i32) -> i32 {
// Implicit return (no semicolon)
x + y
}
// Main function
fn main() {
// Numbers //
//
// Immutable bindings
let x: i32 = 1;
// Integer/float suffixes
let y: i32 = 13i32;
let f: f64 = 1.3f64;
// Type inference
// Most of the time, the Rust compiler can infer what type a variable is, so
// you dont have to write an explicit type annotation.
// Throughout this tutorial, types are explicitly annotated in many places,
// but only for demonstrative purposes. Type inference can handle this for
// you most of the time.
let implicit_x = 1;
let implicit_f = 1.3;
// Arithmetic
let sum = x + y + 13;
// Mutable variable
let mut mutable = 1;
mutable = 4;
mutable += 2;
// Strings //
//
// String literals
let x: &str = "hello world!";
//
// Printing
println!("{} {}", f, x); // 1.3 hello world
//
// A `String` a heap-allocated string
let s: String = "hello world".to_string();
//
// A string slice an immutable view into another string
// This is basically an immutable pair of pointers to a string it doesnt
// actually contain the contents of a string, just a pointer to
// the begin and a pointer to the end of a string buffer,
// statically allocated or contained in another object (in this case, `s`)
let s_slice: &str = &s;
//
println!("{} {}", s, s_slice); // hello world hello world
// Vectors/arrays //
//
// A fixed-size array
let four_ints: [i32; 4] = [1, 2, 3, 4];
//
// A dynamic array (vector)
let mut vector: Vec<i32> = vec![1, 2, 3, 4];
vector.push(5);
//
// A slice an immutable view into a vector or array
// This is much like a string slice, but for vectors
let slice: &[i32] = &vector;
//
// Use `{:?}` to print something debug-style
println!("{:?} {:?}", vector, slice); // [1, 2, 3, 4, 5] [1, 2, 3, 4, 5]
// Tuples //
//
// A tuple is a fixed-size set of values of possibly different types
let x: (i32, &str, f64) = (1, "hello", 3.4);
//
// Destructuring `let`
let (a, b, c) = x;
println!("{} {} {}", a, b, c); // 1 hello 3.4
//
// Indexing
println!("{}", x.1); // hello
}