What do "re:" and "im:" mean in Rust?

Asked

Viewed 1,288 times

6

I want to know what re and im mean/do

let mut z = Complex { re: 0.0, im: 0,0 };

I’m learning Rust by the book Programming Rust and this re: and im: it must have appeared before, but only now have I bothered to research.

What I found before I got here was that im: is a way to create immutable code structures (free translation of: immutable data Structures), but nothing about the re, that kick that can be reusable.

Another thing I thought of im: was also in Rust’s documentation where it said it was a Crate, then I’m not sure if it’s something else entirely (this is the only dependency listed in Cargo.toml "num = "0.1.27"")

  • 2

    Have you studied complex numbers before? It consists of a real part (Re) and an imaginary part (Im).

2 answers

10


Rust allows you to initialize an object with a literal form. This form is composed by the name of the type, of keys that will indicate the beginning and end of this literal, as if it were the quotation marks of a string, and then you put the members who want to initialize the object data.

Rust has no constructor like other languages, it may have simple functions that serve as constructors, but the most commonly used form is the pure and simple initialization of this form of literal.

So it looks like a function call with named arguments, only what you’re doing is using the names of the members of the struct and its values. So what is before the : is the name of the member and what is after the : is the value to be attributed to that member.

In this example you’re a guy Complex, re is the real part of the number and im is the imaginary part. It has nothing to do with what you speculated in the question, it is much simpler than this. This information has to do with the type of data there, the Complex and not with language rules. The language only determines the syntax of this object initializer.

Another hypothetical example:

let joao = Funcionario { nome : "João", salario : 1000 };

I put in the Github for future reference.

Get it? They’re just members of the struct, And by the way, by the way, by the way, by the way, you look like a C, not a Rust.

6

This has no relation to immutable or reusable.

Probably at some point in the book a structure similar to:

struct Complex {
    re: f64,
    im: f64
}

Representing a complex number. re represents the real part, while im represents the imaginary part.

In doing:

let mut z = Complex { re: 0.0, im: 0.0 };

You’re basically creating an object z, which follows the structure Complex, having a zero value in both the real and imaginary parts.

You can read more about struct in Using Structs to Structure Related Data.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.