Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are nested structs supported in Rust?

Tags:

struct

rust

When I try to declare a struct inside of another struct:

struct Test {     struct Foo {} } 

The compiler complains:

error: expected identifier, found keyword `struct`  --> src/lib.rs:2:5   | 2 |     struct Foo {}   |     ^^^^^^ expected identifier, found keyword help: you can escape reserved keywords to use them as identifiers   | 2 |     r#struct Foo {}   |     ^^^^^^^^  error: expected `:`, found `Foo`  --> src/lib.rs:2:12   | 2 |     struct Foo {}   |            ^^^ expected `:` 

I could not find any documentation in either direction; are nested structs even supported in Rust?

like image 422
abergmeier Avatar asked May 13 '14 10:05

abergmeier


People also ask

Does rust have structs?

Structs in Rust come in three flavors: Structs with named fields, tuple structs, and unit structs. Regular structs are the most commonly used. Each field defined within them has a name and a type, and once defined can be accessed using example_struct. field syntax.

Can structs have functions rust?

Rust uses a feature called traits, which define a bundle of functions for structs to implement. One benefit of traits is you can use them for typing. You can create functions that can be used by any structs that implement the same trait.

How do I make an instance of a struct in Rust?

We create an instance by stating the name of the struct and then add curly brackets containing key: value pairs, where the keys are the names of the fields and the values are the data we want to store in those fields. We don't have to specify the fields in the same order in which we declared them in the struct.

How do you create objects in Rust?

In rust we do not create objects itself, we call them instances. To create a instance you just use the struct name and a pair of {}, inside you put the name of the fields with values.


1 Answers

No, they are not supported. You should use separate struct declarations and regular fields:

struct Foo {}  struct Test {     foo: Foo, } 
like image 141
Vladimir Matveev Avatar answered Oct 21 '22 23:10

Vladimir Matveev