Rust naming for creating sub objects

  1. I have some code that looks like this:
pub struct Foo {}
pub struct Bar {}

impl Foo {

  pub fn some_name(&mut self, ...) -> Bar {}

}
  1. The names new.* seems like they should be free functions that create a Foo from scratch and return it.

  2. However, these are functions that take a (&mut self, ...) and return a Bar. Is there a standard naming convention for this?

There isn't really a standard way to write something like this. It's usually dependent on how similar Foo and Bar are. Is "Bar" some kind of representation of a part of "Foo", like a name or an ID (in which case, it would probably be get_bar)? Is "Bar" a handle that you can use to edit part of "Foo" (in which case, it would be named something like open_bar or slice_bar)? Is "Bar" an object that will exist within "Foo" (in which case, it would be something like add_bar)?

There's no naming convention for "factory pattern" like methods, because it's usually done the other way:

Bar::with_foo(&mut foo)
2 Likes

So in my particular case, I have a "NumEnv" class, which holds things like blas handles / gpu handles / etc ... and I am curently having this class create Tensors for me, so something like:

impl NumEnv {
  pub fn new_ten0() -> Ten0 ...
  pub fn new_ten1(d0: isize) -> Ten1 ...
  pub fn new_ten2(d1: isize, d2: isize) -> Ten2 ...
}

I don't like this naming convention as the num_ functions are returning Ten* objects, not NumEnv objects.

You are saying the 'more Rusty' pattern would be to do

impl Ten0 {
  pub fn new0(env: &mut NumEnv) -> Ten0 ....
}

impl Ten1 {
  pub fn new1(env: &mut NumEnv, d0: isize) -> Ten1 ....
}

impl Ten2 {
  pub fn new2(env: &mut NumEnv, d1: isize, d0: isize) -> Ten2 .... 
}

?

Yes, e.g. Ten1::with_env(d0, env), or if env is obvious and always needed, maybe even Ten1::new(d0, env).

I'd say foo.create_bar() is fine.