Struck not accepting f32 directly (bug?)

This works:

struct Food {apples:f32, bananas:f32}

fn main () {
	
	let apples:f32 = 1.0;
	let bananas:f32 = 2.0;
	
	let Fruits = Food{apples, bananas};
	println!("Number of apples: {}", Fruits.apples);

This does not work:

struct Food {apples:f32, bananas:f32}

fn main () {
	
	let apples:f32 = 1.0;
	
	let Fruits = Food{apples, 3.0};
	println!("Number of apples: {}", Fruits.apples);

Is this a bug in the compiler or is it by design?

Usually when you create an instance of a struct you have to list the field names, like this:

let apples = 2.0;
let bananas = 3.0;
let f = Food { apples: 2.0, bananas: 3.0 };
// or
let f = Food { apples: apples, bananas: bananas }

In case you use a variable for initializing a field and that variable has the same name as the field you want to initialize, you can omit the field's name:

let f = Food { apples, bananas }
// or
let f = Food { bananas, apples }
// or, for example
let f = Food { bananas: bananas, apples }

But literal values don't have a name of course, so you need to manually specify which struct field to assign it to.

4 Likes

Alright.

It's almost never a compiler bug. Read: especially when you are learning the language, you cannot reasonably expect to find a real, honest compiler bug. It's overwhelmingly more likely that your understaning or expectations of the language are flawed.


Of course, this is by design. Rust's struct fields are named, and field names carry semantics to a human reader. The compiler doesn't blindly initialize fields in declaration order because then accidentally interchanging two fields of the same type would be silently accepted and do the wrong thing. Rust's philosophy is all about correctness, and not being able to accidentally misuse the code.

3 Likes

Okay, Im new to rust. Just trying to learn and understand. Thank you both for your replies.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.