finished structs ch

This commit is contained in:
2025-01-06 13:26:57 -07:00
parent 1f56ecfb24
commit 507d3920b1
3 changed files with 40 additions and 3 deletions

View File

@ -168,6 +168,7 @@ must be explicity typed to true or false
let n = false;
let o = true;
```
&& is and operator
### Char
must use single quotes and not "" otherwise will be inferred as string literal
@ -550,6 +551,11 @@ impl Rectangle {
fn area (&self) -> u32 {
self.length * self.width
}
// this is an example of a mthod with exterior params requried
fn fit_into (&self, other: &Rectangle) {
self.length > other.length && self.width > other.width
}
}
```
@ -572,4 +578,35 @@ just differenitate with the use of () this is for a mthod not the field
this is used in getters where you want read only access to a struct, you can make the field pravate but the method public
130
## Associated Functions
functions in the impl block are associated with the struct
all functions within tthe impl block is associated functions
not all associated methods have a self reference and therefore arent methods
can be used in constructors or destructors, often constructors are what they are used for
new is often used for constructors, not a protected keyword
example
```rust
impl Rectangle {
// Self is only allowed within the impl scope, referes to what the scope is for, this determines the return type
fn square(side: i32) -> Self {
Self {
length = side,
width = side,
}
}
}
```
to call these types of functions use the :: operator, this is also used in namespaces
ex
```rust
let square1 = Rectangle::square(3);
```
you have have multiple impl blocks associated with a struct, is the same as hvaing one monolithic one (better for readibility)
some use cases for multiple impl blocks