Difference Between Type and Struct

This might be a dumb question, but I am not sure what the difference is between a type and a struct. They both seem to be definitions of groupings of variables that can then be used to declare new instantiations of their category.

type Foo = ...; outside of an impl block is a type alias, which means it does not define a new type, just an additional name for an existing type. You cannot define separate member functions or implement traits on a type alias distinct from the aliased type. E.g. type Foo = i32; is the same type as i32.

Inside of an impl block, type Foo = ...; is an associated type, which are primarily used in traits, allowing the type implementing the trait to specify types that will be used by the trait. For example, the Iterator trait has an Item associated type, allowing the implementer to specify what type the iterator produces. Associated types are still fundamentally type aliases, in-so-far as they don’t define new types, just aliases for other types.

struct Foo { ... } or struct Foo(...); defines a new type, which can have member fields, member functions, and have traits implemented on it. It’s a unique type distinct from its composite fields. E.g. struct Foo(i32); is different type from i32.

1 Like

Essentially, a type is the name for a set of values that can be assigned to a variable. For instance, the type bool has the values true and false, and the type [bool; 2] has the values [true, true], [true, false], [false, true] and [false, false].

Structs (as well as enums) are a means to define new types.

Enums are sometimes called “sum types”. Likewise, structs and tuples are called “product types”.

With generics, you can even define multiple types at once, since Foo<Bar> is a different type than Foo<Baz> or Foo<(Bar, Bar)>.

1 Like

A struct is a type-- “type” is the more general category; struct is one kind of type. Other kinds of types are enums, scalar primitive types, and compound primitive types.

The core Rust language defines the primitive types and the mechanism by which new structs and enums can be created. The standard library defines more structs and enums such as String and Option<T>, and you can define your own structs and enums.

The reference has a really technical section on types that you might also be interested in.

Does that help? :slight_smile: