Created
November 26, 2023 18:55
-
-
Save i-asimkhan/bb55078fe9da6a5731f1c2860ee9e72e to your computer and use it in GitHub Desktop.
Stack and Heap in #Rust
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
mod stack_heap_example; | |
use crate::stack_heap_example::stack_and_heap; | |
#[allow(dead_code)] | |
#[allow(unused_variables)] | |
fn main() { | |
stack_and_heap(); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#![allow(dead_code)] | |
use std::mem; | |
struct Point { | |
x: f64, | |
y: f64 | |
} | |
fn origin() -> Point { | |
Point{x:0.0, y: 0.0} | |
} | |
pub fn stack_and_heap() { | |
let p1 = origin(); | |
let p2 = Box::new(origin()); | |
println!("Object p1 takes up {} bytes", mem::size_of_val(&p1)); | |
// p2 will take less becasue it stores address of the p1 | |
println!("Object p2 takes up {} bytes", mem::size_of_val(&p2)); | |
let p3 = *p2; | |
println!("Object p3 takes up {} bytes", mem::size_of_val(&p3)); | |
println!("Object p1 value for x,y {},{} bytes", p1.x, p1.y); | |
println!("Object p3 value for x,y {},{} bytes", p3.x, p3.y); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment