Understanding Rust Struct Initialization and Colon Semantics

Encountered a question during the learning process, and after a brief discussion with a friend, I found that JavaScript is also like this.
Specifically, I have doubts about the semantics of the colon.
For example: Defining a struct

struct Foo {
    ctx: String
}

Trying to initialize the struct, I created a temporary String and moved it to the memory of the struct member

let foo = Foo{ctx: String::from("val")}; //Here, the colon after ctx should mean initialization through assignment

Since the colon represents assignment, theoretically, I could also use the assignment operator

let foo = Foo{ctx = String::from("val")}; //Error

So I'm a bit confused.

Summarizing the questions:

  1. Does the aforementioned colon express the meaning of assignment? If it does not express the meaning of assignment, what exactly does it do?
  2. If it expresses the meaning of assignment, why would one consider restricting the assignment for member initialization to a colon?

Does it “express the meaning of assignment”? Well, this is debatable, but I would say that while it does associate a field with its value, that association is not an assignment. There are particular semantics assignment has that struct literal fields don’t, and vice versa. More significantly, struct literals work as patterns too, which is not at all like assignment, because the data flows in the opposite direction:

let foo = Foo {
    ctx: String::from("val"),
};
let Foo { ctx: ctx_str } = foo;
println!("{ctx_str}");

But another question one could ask is: could Rust have chosen to use = instead of : in struct literals? And the answer to that question is yes, absolutely, there are no obstacles to it. It’s one of the many semi-arbitrary choices every programming language’s syntax must make.

5 Likes

Thank you for your reply.
I'm still not clear on pattern matching, but the example you provided has essentially answered my question. The second statement you gave has shown that using ":" can avoid ambiguity in data flow with "=", which I think is sufficient reason for Rust not to design it that way in struct literals. :blush:

1 Like