I started with Rust around two weeks ago. I am now in chapter 6 of the book. And I think, I identified one general aspect, which us not clear for me and which makes my progress dificult. (Please, forgive me my unclear english especially according to programming terminology.)
First - I have some (pretty outdated) experience with LPC programming language, which is of C family. I didn't need to take care about namespaces there. (I mean :: ). Actualy - it was used, but only in case there was doubleinheritance of a function (function was defined in more parent objects) or I wanted to override a function, but needed to keep also functionality of this function from parent object.
In Rust I understand that I need to use "full path" to get to the desired function (or method). But already in Guessing game there are points I do not fully grasp.
use std::io; io::stdin().read_line(&mut guess).expect("Failed to read line");
I am comfortable with "stdin()" function being part of "io" module, which is part of "std" crate. But:
is read_line() method (or "handle", whatever does it mean) part of stdin() function? And expect() part of read_line()? I know, this will be explained later, but then I run into this:
use rand::Rng;
let secret_number = rand::thread_rng().gen_range(1, 101);
Why there needs to be Rng, when it is not used in syntax. I would understand following syntax:
use rand;
let secret_number = rand::thread_rng().gen_range(1, 101);
I can live even with this to later stages, but then I found myself struggling with basic aspects like this:
Why there are two different ways to access values in array on one side and values in tuple on other side:
my_array[1] vs. my_tuple.1. I am able to remember correct syntax, but I don't understand, why is it different.
And especially structs:
struct Rectangle { x: u32, y: u32 }
impl Rectangle {
fn area(&self) -> u32 {
self.x * self.y
}
fn square(n: u32) -> Rectangle {
Rectangle {x:n, y:n }
}
}
fn main(){
let rect1 = Rectangle {x: 20, y:30};
let area = rect1.area();
let rect2 = Rectangle::square(10);
}
Why cannot I write Rectangle.square(10)? I understand, dot is used to access instance of Rectangle and :: is used when there is no instance. I can remember correct syntax, but I need to understand why is it done this way.
I think, I am unable to dive deeper into the language unless I understand this basic stuff. Please, can you help me out or give a link to explanations? Thank you very much.