Generic Struct Example in Rust

preview_player
Показать описание
Use a generic struct to accept float or integers.
(add angle brackets as the suffix to the name of the struct)

A generic struct acts as an abstract stand-in for a yet to be chosen data type
(The data type gets specified at compile time based on what you decide to use with your variable types).

Without this, you would get a compiler error if you specified a data type different to what was specified for the struct field.

It would be amazing if you want to support my channel via Patreon:

#Rust #beginnertutorial #rusttutorial
Рекомендации по теме
Комментарии
Автор

Please don't do this man...

First and foremost to make the code more readable for all please run cargo fmt on it.

Second, this is a completely unrestrained generic which is very useful 0.1% of the time and utterly useless 99.9% of the time, because I could put anything in it, I can make up my own type and throw it in there whether it makes sense or not. The aforementioned overflexibility is alleviated in 1 of 2 ways usually, the first is with constraining the generic with trait bounds, which reduces the possible type pool to only types which implement a certain trait, when this is not applicable or just is excessive, an enum is usually used instead to limit the possible options.

For this example I'd just use f32 anyways because floats can store whole numbers too anyways.

dyslexicsteak