Basic struct and enum questions


#1

I was curious why structs and enums have a trailing comma in their syntax.

Why this:

struct MyStruct {
    field1: String,
    field2: String, <-- trailing comma
}

and not this

struct MyStruct {
    field1: String,
    field2: String <-- no comma
}

Also, what is the Rust way to create a struct with one field that should never change and other fields that are fine. so

struct MyStruct {
    MyStructID: int; <-- this field should never change once instantiated.
    field1: String,
    field2: String,
}

let mut my_struct MyStruct makes all the field mutable.

In OOP you would just make it a private variable that gets set by the constructor and only has a read method in the public API.


#2

The comma after the last field is optional. One reason for including it is so you can later add a new field just by adding a line, without changing any existing lines. This prevents mistakes, and also makes diff output easier to read.

You would do the same in Rust. Make read-only fields private, and do not provide public setters. Code outside the current module will not be able to mutate those fields.


#3

Ah. So if the struct is defined in a library and imported then I can encapsulate the field that way. Cool.

Thanks!


#4

For your own projects its enough if the struct is in another module. The default for fields is to be private to the module they’re defined in.

Fields that are read-only publicly would be nice to have. Unfortunately, not there yet.


#5

Thanks. Still working out the details of scope/crates/modules, etc. But I think I see how to organize things a little better now.