What is the best way to use unit-like struct?

struct A;

impl A {
    fn a(&self) {
        println!("{:?}", self.b());
    }
    fn b(&self) -> &str {
        "b"
    }
}
fn main() {
    let mut i = 0;
    loop {
        i += 1;
        A.a();
        if i > 100 {
            break;
        }
    }
}


If invoke the "A.a()" so much times, should hold it somewhere , do like this:

struct A;

impl A {
    fn a(&self) {
        println!("{:?}", self.b());
    }
    fn b(&self) -> &str {
        "b"
    }
}
fn main() {
    let mut i = 0;
    let a = &A;
    loop {
        i += 1;
        a.a();
        if i > 100 {
            break;
        }
    }
}

Why does A exist at all in this situation? Why not just have free functions in a module if you want namespacing?

Either way, there's really no reason to cache an A like that. A contains no data, so it need never exist in the first place. Heck, if you check the generated LLVM IR, you'll see that self never even gets passed to those methods. Why? It contains zero information; there's no point.

Instead of a struct, it might be more rustic to use a const str and a function

const HELLO_WORLD: &'static str = "Hello world";

fn print_hello() {
    println!("{}", HELLO_WORLD);
}

fn main() {
    for _ in 0..10 {
        print_hello()
    }
}

Edit. But if you like structs, then you can also do the following

struct Hello;

impl Hello {
    fn greet() {
        println!("Hello World");
    }
}

fn main() {
    for _ in 0..10 {
        Hello::greet();
    }
}
1 Like

i am a newbie to rust, just trying to make a sample and fuss messing about the unit-like struct, but now,thanks ,i got it

1 Like

nice

1 Like

I probably should have elaborated, but the main use for unitary structs are for things like error types where there's no extra information, or as generic parameters where you need to pass a type, but you want to pass a bundle of trait implementations.

2 Likes

Also for messing with the type system (though I am reliably informed that empty enums are the better solution there because they cannot accidentally be instantiated).

Oh, void types are a whole different marine-animal-filled aparatus for the heating of water.

1 Like