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


#1
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;
        }
    }
}


#2

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.


#3

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();
    }
}

#4

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


#5

nice


#6

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.


#7

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).


#8

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