Skip to content

Instantly share code, notes, and snippets.

@max-itzpapalotl
Last active January 7, 2024 12:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save max-itzpapalotl/818843e3e38f3daf7c4bf29c1692b57a to your computer and use it in GitHub Desktop.
Save max-itzpapalotl/818843e3e38f3daf7c4bf29c1692b57a to your computer and use it in GitHub Desktop.
6. Structs and Methods

6. Structs and Methods

  • Struct types
  • Tuple Structs
  • Methods and their use
  • Private and public data, access rules

Struct definitions

#[derive(Debug)]
struct S {
    id : u64,
    name : String,
}

fn main() {
    let s : S = S{
        id : 12,
        name : "Mustermann".to_string(),
    };
    println!("{:?} {} {}", s, s.id, s.name);
}

Tuple Structs

#[derive(Debug)]
struct S(u64, String);

#[derive(Debug)]
struct U;

fn main() {
    let s : S = S(12, "Mustermann".to_string());
    let u : U = U;
    println!("{:?} {} {} {:?}", s, s.0, s.1, u);
}

Methods

#[derive(Debug)]
struct S {
    id : u64,
    name : String,
}

impl S {
    fn new(c : u64, s : &str) -> S {
        S{id: c, name: s.to_string()}
    }
    fn show(&self) {
        println!("S: id={} name={}", self.id, self.name);
    }
    fn inc(&mut self) {
        self.id += 1;
    }
}

fn main() {
    let s : S = S{
        id : 12,
        name : "Mustermann".to_string(),
    };
    let mut s2 = S::new(1u64, "Mueller");
    s2.inc();
    s2.show();

    println!("{:?} {} {} {:?}", s, s.id, s.name, s2);
}

Private and public data

mod m {
    #[derive(Debug)]
    pub struct S {
        pub id : u64,
        name : String,
    }

    impl S {
        pub fn new(c : u64, s : &str) -> S {
            S{id: c, name: s.to_string()}
        }
        pub fn show(&self) {
            println!("S: id={} name={}", self.id, self.name);
        }
        pub fn inc(&mut self) {
            self.id += 1;
        }
    }
}

fn main() {
    let mut s = m::S::new(1u64, "Mueller");
    s.inc();
    s.show();

    println!("{:?} {}", s, s.id);
}

References:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment