Skip to content

Rust Style Conventions #692

@JeremyRubin

Description

@JeremyRubin

My understanding of naming:

* `new` - obvious constructor, may be empty (`String::new()`, `Box::new(T)`)
* `from_` - takes _same_ information as `new` just in different representation (e.g. `String::from_utf8(Vec<u8>)`)
* `with_` - takes _additional_ information along with what `new` takes `String::with_capacity(usize)`

I thought String was a bit of a special case but a quick look at the std lib shows its not. Perhaps conventions have changed for more recent code? I was under the impression that

  • Constructors with zero args should use Default
  • Constructors with one arg should use From<Foo> (unless the foo needs further restriction like the String;:from_utf8 case)
  • Constructors with multiple args should use new.
  • Constructors using the builder pattern should use with(self, foo: Foo)

I've never managed to work out the pattern for times when we need multiple constructors with multiple args?

Amusingly I was looking at all the instances of single arg constructors for Script yesterday wondering why they used the pattern new_.

I don't mean to bike shed here, I'm genuinely interested in these sorts of conventions.

Originally posted by @tcharding in #677 (comment)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions