Misc 8 @adotinthevoid

Warning: this quiz is still "work-in-progress", some questions might not have good explanations (or any at all), formatting/structure/titles/etc are not final, and so on. You might want to return here on a later date.

struct bar {}
fn bar() {}

struct foo();
fn foo() {}
Solution
error[E0428]: the name `foo` is defined multiple times
 --> examples/misc_8.rs:8:1
  |
7 | struct foo();
  | ------------- previous definition of the value `foo` here
8 | fn foo() {}
  | ^^^^^^^^ `foo` redefined here
  |
  = note: `foo` must be defined only once in the value namespace of this module

For more information about this error, try `rustc --explain E0428`.
error: could not compile `code` (example "misc_8") due to 1 previous error

There are 3 kinds of structs in Rust:

  1. Plain structs (eg struct Foo { bar: i32 })
  2. Tuple structs (eg struct Bar(i32);)
  3. Unit structs (eg struct Baz;)

All 3 kinds can have a struct with no fields.

Types and values live in separate namespaces, as it is usually 1 possible to syntactically determine whether an identifier the compiler needs to resolve will be an value or type .

1

except when it isn't :)

This means that struct bar {} only gets inserted into the type namespace, and fn bar only gets inserted to the value namespace (as functions in Rust are first class values [^not]). Therefore both of these declarations can co-exist.

However for struct foo, because it's a tuple struct, it also needs to insert the constructor into the value namespace. (This isn't quite the same as inserting a function, as it's also valid in pattern matching, but it's close). This then clashes with fn foo, which also lives in the value namespace, causing the compiler error.

[^not] except when they're not :)