This is a code style question, there are many cases where you can use functions in place of a struct, for example
struct Printer {
foo: String,
}
impl Printer {
fn print() {
println!("{}", self.foo);
}
}
and
fn run(foo: String) {
println!("{foo}");
}
are the same and the latter obviously makes more sense but where is the line in this kind of usage? Like in
struct Printer {
foo: String,
bar: String,
baz: String,
}
impl Printer {
fn print_all(self) {
self.print();
self.eprint();
}
fn print(&self) {
println!("{},{},{}", self.foo, self.bar, self.baz);
}
fn eprint(&self) {
eprintln!("{}", self.foo, self.bar, self.baz);
}
}
and
fn print_all(foo: String, bar: String, baz: String) {
print(foo, bar, baz);
eprint(foo, bar, baz);
}
fn print(foo: String, bar: String, baz: String) {
println!("{},{},{}", foo, bar, baz);
}
fn eprint(foo: String, bar: String, baz: String) {
eprintln!("{}", foo, bar, baz);
}
the struct really reduces repetition in the code, and it also brings the print methods closer together
But there are cases that make structs less clean than functions too, especially with references, for example
struct Runner<'a, 'b> {
ctx: &'a mut Context<'b>,
}
impl<'a, 'b> Runner<'a, 'b> {
fn foo(&self)
}
and
fn foo(ctx: &mut Context)
So I'm asking how do you decide which pattern you use in your code? Thank you!