-
Notifications
You must be signed in to change notification settings - Fork 0
Defining Structs
Time to start writing some code. We need something to represent a bank and we need to make something to represent an account. A bank is going to have multiple accounts tied to it from zero to 10, 20 or 30 and beyond. Tied to bank and account we want to have some set functionality.
So the bank and account objects should have some different methods and associated functions tied to them and the bank should be represented using some type of struct and same thing for account, so two different structs like so:
struct Account {}
fn main() {
println!("Hello, world!");
}
Inside of our Account
struct we are going to have a couple of different fields, we are going to have a balance, that will be a positive integer. We will store this as a signed integer where 1023 will represent $10.23. The id will be an Unsigned Integer because it doesnt really make sense to have a negative id. Finally, a holder will be the name of the person who holds this account. So we will add in these fields to our Account
struct definition.
struct Account {
id: u32,
balance: i32,
holder: String,
}
fn main() {
println!("Hello, world!");
}
At some point in time we are probably going to want to print out an Account
so we can debug it. To do that we add on that attribute of derive debug like so:
#[derive(Debug)]
struct Account {
id: u32,
balance: i32,
holder: String,
}
fn main() {
println!("Hello, world!");
}
We now make a bank struct and have some kind of list of accounts like so:
#[derive(Debug)]
struct Account {
id: u32,
balance: i32,
holder: String,
}
struct Bank {
accounts:
}
fn main() {
println!("Hello, world!");
}
And we probably want this to be a list that can grow and shrink in size and a really good type to use for that would be a vector because vectors can grow and shrink in size:
#[derive(Debug)]
struct Account {
id: u32,
balance: i32,
holder: String,
}
struct Bank {
accounts: Vec<>
}
fn main() {
println!("Hello, world!");
}
Whenever we define a vector type we place the angle brackets and contain a list of Account
structs like so:
#[derive(Debug)]
struct Account {
id: u32,
balance: i32,
holder: String,
}
struct Bank {
accounts: Vec<Account>
}
fn main() {
println!("Hello, world!");
}
We are also going to want to print out a bank at some point in time for debugging purposes so will have to list out derive debug at the top once again like so:
#[derive(Debug)]
struct Account {
id: u32,
balance: i32,
holder: String,
}
#[derive(Debug)]
struct Bank {
accounts: Vec<Account>
}
fn main() {
println!("Hello, world!");
}