A list of puns related to "Enum"
I've been wondering about something lately. Take this code:
fn main() -> Result<(), String> {
let my_var: Result<String, String> = Ok("some_string".to_string());
if let Err(err) = my_var {
return Err("Oh not".to_string()) // Return something in this block - we now know that the enum cannot be an Err variant below this block
}
// We _know_ that my_var is a Ok(String) here - but I still have to call unwrap on it
my_var.chars(); // This is not valid
Ok(())
}
Is there a reason that the Rust compiler doesn't automatically narrow the type here - like a language like TypeScript might do. Is this something that's been considered and rejected?
Hi all,
Is there a better way to do this...?
Imagine an Enum with this in...
public enum LocalMeters {
_VALUE (SystemMeters._MAX_SYSTEM_METERS.get()),
_BAD_PLAYER_ACTION (_VALUE.meterNum),
_DUMMY_METER (_VALUE.meterNum+1);
...
...
...
}
The problem with doing this is I'd have to renumber all the meters below any that I insert.
If there's a better way to do something like this I'd be very grateful for the help.
TIA
I often need to read and write enums to file. Initially I did this by converting them from and to integers. To make the enums more readable I decided to store them as strings instead (in file). However now I had to create dictionaries, ex std::map<std::string,MyEnum>
and std::vector<std::string>
for each enum. When I had just a couple of enums I filled the dictionaries manually, but now I need a better solution.
The closest I've come to so far is the code below using preprocessor. But I would still have to write this code for each individual enum. Is there a better solution to this problem than this horrible mess?
#define FOREACH_FRUIT(DO) \
DO(APPLE) \
DO(ORANGE) \
DO(GRAPE) \
#define GEN_ENUM(VAR) VAR,
#define GEN_STRING(VAR) #VAR,
enum FRUIT {
FOREACH_FRUIT(GEN_ENUM)
};
void generateDictionary() {
std::vector<std::string>strings = {FOREACH_FRUIT(GEN_STRING)};
std::vector<FRUIT>enums = {FOREACH_FRUIT(GEN_ENUM)};
std::map<std::string,FRUIT>dictStringEnum;
std::vector<std::string>dictEnumString; //can use vector because enum will have default values
for (size_t i = 0; i < strings.size(); i++) {
dictStringEnum[strings[i]] = enums[i];
dictEnumString.push_back(strings[i]);
}
}
Edit: fixed some typos in code
Hi folks, I recently upgraded a couple of old interconnected Framework 4.5 apps to a slightly less old 4.8 and made a couple of changes to the structure of the object sent between them.
One app writes a serialised object into a StreamWriter
and posts it to an API method on the other. They both reference the object being posted via a shared library.
The issue I have is that the receiving app now returns a 500 error:
> InvalidCastException: Unable to cast object of type 'Company.Enums.MyEnum' to type 'System.Array'.
The enum is serialised as numeric, but I don't understand why the framework is trying to bind this value to an array, rather than the same enum it has referenced in the method signature, any ideas?
EDIT: resolved, the Source
property had a MaxLength
attribute, presumably this caused it to be treated as a string?
Suppose I have a method that accepts a System.Enum as a parameter and I have enums A, B, and C.
One of A, B, and C will be fed into the method, which will then dispatch to other methods in a sort of Factory pattern to create objects.
My question is: how do I switch on the name of the enum (A, B, or C) rather than the contents of the enum?
It appears that the GetName method on an enum returns the member name, which I will need only in a later step
I'm thinking about using enums something like this
public enum State {
Idle,
Run,
Jump
}
State state;
...
switch(state){
case States.Idle:...
but how good is this for performance, compared to just an array of ints?
I'm a newbie in rust currently in the process of learning it. I was wondering if there is a way in which I can get the `length` of the enum that I am defining. If there is then how should I go about finding it?
[Editted]
Since many of you were asking why I want to find the length of the enum, here is why. So basically my enums define different blocks in my TUI program. Now I want to navigate using my arrow keys through these blocks. To check if I have cycled through all the blocks, I would need the length of my enum.
(NOTE #1: This enum is not only used here but it also is used elsewhere as well. I know I am better off with a `Vec<_>` but I just wanted to know if I can get the length of the enums.)
(NOTE #2: Currently since I know exactly how many blocks I have in my TUI, I am just assigning that value and making things work. If I don't find any proper solution, I would just create a `Vec` and use it's `len()` method for it.)
(NOTE #3: Below I am attaching the current implementation as well as what I mean by TUI block for reference.)
--------------------------------------------------------------
| block 1 |
--------------------------------------------------------------
--------------------------------------------------------------
| block 2a | block 2b |
--------------------------------------------------------------
--------------------------------------------------------------
| block 3 |
--------------------------------------------------------------
Current Implementation (just giving the idea here):
enum Focus {
block1,
block2,
block3,
}
impl Focus {
fn from(items: Focus) -> usize {
match items {
Focus::block1 => 0,
Focus::block2 => 1,
Focus::block3 => 2,
}
}
fn from_usize(items: usize) -> Focus {
match items {
0 => Focus::block1,
1 => Focus::block2,
2 => Focus::block3,
_ => {}
}
}
}
struct App {
current_focus: Focus,
}
impl App {
fn new() -> Self {
Self { current_focus: Focus::block1 }
}
fn next(&mut self) {
let current_focus = Focus::from(self.current_focus);
let total_focus_blocks = 4; // Need to Enum length here
if cu
... keep reading on reddit β‘I've been looking into enums in Go, and how to convert them back into their string value. Online I've found quite some different ways, with this one being the one (seemingly) used the most:
type MyEnum int
const (
Foo MyEnum = iota
Bar
)
func (me MyEnum) String() string {
return [...]string{"Foo", "Bar"}[me]
}
fmt.Println(Foo, Bar) // Prints: Foo Bar
Now, while this works, it does seem to me as quite 'unsafe' as there are now 2 locations where the enum is being kept, so if someone would make a type in either location, or somehow changes up the order, this would fail to work (stop working or just give a wrong result). Isn't there any better way to handle this, where the enum could just be defined on one place? Or is this the cleanest option anyways?
https://www.youtube.com/watch?v=3Ga-wrXZLHc
I hope this helps. I intend my videos to be completely unscripted so you see the mistakes I make and how I correct them, and also my thought processes.
I'm a developer by trade and even though I have done this a long time, it's good to hear how developers think and how they go about designing solutions.
Any questions, please contact me. Duster76#3746 on Discord.
Edit: Still processing HD version as of 2030GMT, give it time
https://github.com/zhiburt/tabled
There is a list of main additions.
An example bellow shows usage of each of these features.
use tabled::{Border, Concat, Highlight, Style, TableIteratorExt};
fn main() {
let data = vec[["A", "B", "C"], ["D", "E", "F"], ["G", "H", "I"]];
let table = (0..data.len())
.table()
.with(Concat::horizontal(data.table()))
.with(Style::PSEUDO)
.with(Highlight::cell(
2,
2,
Border::full('*', '*', '*', '*', '*', '*', '*', '*'),
));
println!("{}", table);
}
The printed result.
βββββββββ¬ββββ¬ββββ¬ββββ
β usize β 0 β 1 β 2 β
βββββββββΌββββΌββββΌββββ€
β 0 β A β B β C β
βββββββββΌβββ*****ββββ€
β 1 β D * E * F β
βββββββββΌβββ*****ββββ€
β 2 β G β H β I β
βββββββββ΄ββββ΄ββββ΄ββββ
In C99, instead of using macro defines and for purpose of code style and syntax highlighting, can I design my API legally and safely while mixing names between enum namespace and primitive type namespace like in the hypothetical example below? I can imagine thee would be portability issues with like C++, but the code is and will remain to be specifically for plain C99 (or later) only.
typedef Int32 EAudioStreamDataFormat; /* predefined fixed size type */
/* I would like to not do it like: */
/* #define AUDIO_STREAM_DATA_FORMAT_UNKNOWN 0 */
/* #define AUDIO_STREAM_DATA_FORMAT_FLOAT 1 */
/* #define AUDIO_STREAM_DATA_FORMAT_INT16 2 */
/* #define AUDIO_STREAM_DATA_FORMAT_UNSUPPORTED 3 */
/* but I would like to do it like: */
enum EAudioStreamDataFormat /* NOTE: same name as typedef above */
{
EAudioStreamDataFormat_Unknown = 0,
EAudioStreamDataFormat_Float = 1,
EAudioStreamDataFormat_Int16 = 2,
EAudioStreamDataFormat_Unsupported = 3
};
typedef struct AudioStream
{
void* buffer;
EAudioStreamDataFormat format; /* Int32, fixed size type */
Int32 someValue;
} AudioStream;
extern Int32 CreateAudioStream(
EAudioStreamDataFormat format,
Int32 someValue,
AudioStream** ppStream);
Int32 CreateAudioStream(
EAudioStreamDataFormat format,
Int32 someValue,
AudioStream** ppStream)
{
if (EAudioStreamDataFormat_Unknown == format ||
EAudioStreamDataFormat_Unsupported == format)
{
return -1;
}
/* do stuff */
return 0;
}
Int32 errnr;
AudioStream* stream = NULL;
errnr = CreateAudioStream(EAudioStreamDataFormat_Float, 0, &stream);
Most programming languages have enums, but I fail to see any language that allows to extend them. I mean, something like this:
enum Order = (One,Two,Three)
enum Order2 extend Order with (Four, Five)
I am not talking about the syntax details, but the capacity to increase the cases. It feels like something useful if you use a library and want to extend it. In a way, it feels similar to the idea of "traits" that extend a base case but for enums.
Why not to extend enums? (is there any language that does it?)
[C++]
I am trying to set nodes in a maze to have values. The walls will have a higher value so I can find a short path later on.
The walls, empty spaces etc have been established in an enum in a grid class.
enum class griditem { empty, wall, player, target };
I have defined the score I will set for a wall:
constexpr auto WALL = 500;
In a different class, I am struggling to write up a way of setting any walls in the maze to WALL. I've initialised the enum in the class I am trying to pull it to. I have a for loop to go through each node of the maze. But I don't know what to put into the IF statement that will work for making the enum value of wall = my WALL definition.
griditem wall = griditem::wall;
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
if ( )
{
// = WALL definition
}
}
}
The walls are generated randomly:
void Grid::CreateInnerWalls()
{
random_device dev;
mt19937 rng(dev());
CreateFirstWall(rng);
CreateSecondWall(rng);
CreateThirdWall(rng);
CreateRectangles(rng);
CreateFourthWall(rng);
}
Enum.dedup_by([ "a", 'foo', 1, "b", 7, 4, "c", "d"], fn x -> is_integer(x) end ) |> IO.inspect() # ["a", 1, "b", 7, "c"]
I was expecting just the 4 to be dropped like this [ "a", 'foo', 1, "b", 7, "c", "d"] but is has removed all the consecutive duplicates. Am I missing something?
https://preview.redd.it/esvmepqcv4c81.png?width=1029&format=png&auto=webp&s=eb813a4a7c7a7c46ed7ac1992e4be2d6c0a5d6c3
Hey r/godot! I am trying to find some way to export enum naming as the array index instead of the default behavior circled in red. Is this possible? I am new to godot and maybe I am thinking about this in the wrong way.
Basically I would like to have an efficient way of storing and accessing character stats. I am more accustomed to C where we use enums as array indexes all the time. Would it be better as individual variables maybe?
I have found no way to name the indices in the godot documents. I only found ways to export enums as the variable, that is on the right side of the red circled area.
Any suggestions?
Hi.
This is a bit of a silly question, but I'd like to know what you think.
In my WIP I have several state machines. The states those machines can be in are coded as an unnamed enum, like so:
enum {
IDLE,
RUNNING,
JUMPING,
FALLING,
PUSHING,
DRAGGING,
CLIMBING,
}
Often I want to print the state the object is in on the console, for debugging. The values of those constants are integers, so printing it is not very informative, as this
print("The player is now in state %s" % [state])
would print something like "The player is in state 2", while I want it to print "The player is in state JUMPING". My solution for this is to add a dictionary containing the names, like this:
var state_names = {
IDLE:"IDLE",
RUNNING:"RUNNING",
JUMPING:"JUMPING",
FALLING:"FALLING",
PUSHING:"PUSHING",
DRAGGING:"DRAGGING",
CLIMBING:"CLIMBING",
}
and use it to get the name every time I need it. However this looks very "ugly" to me. Another solution would be to have a named enum enum states{ IDLE, RUNNING, JUMPING, FALLING, PUSHING, DRAGGING, CLIMBING, }
And then get the names doing states.keys()[state]
But this would make it so that I have to do states.RUNNING instead of just RUNNING, making my code more verbose.
As I said this is a very silly and minor thing, but I'm curious to know what other people would do in this situation. What would be the best solution here?
I am writing an AST with a lot of different node types, and while performance (and memory usage) generally does not matter much, I am also trying to not to shoot myself in the foot too often. One of the ways I can see that happen easily though is by having bad enum variant size distribution, i.e. most variants use only a word or two of memory, but because I did not pay enough attention i suddenly introduce one that takes 10. With a big tree i am then wasting a lot of memory on unused memory, which of course I want to avoid, if possible without too much hassle. The manual solution would then be e.g. to wrap especially large variants in their own struct and box them for the enum variant.
Is there a lint or other tool i can use to check for such things?
(i could probably introduce a test or check somewhere that makes sure my enum size does not exceed a certain value, but that is not super convenient, even though it is probably the simplest solution)
Hi, I have been thinking about using enums for different sizes of objects,
ex.
SMALL(10), MEDIUM(16), BIG(25);
where the number indicates radius of object
but is this costly?/ is it better to just use their values instead of enum?
I only thought about using enum for easier readability
hi,
I'm trying to do something simple but I can't figure it out. I want to transform a JSON value into an enum in a generic way. This is how far I got:
use json::JsonValue;
use num_derive::FromPrimitive;
pub fn jsonToEnum<T>(json: &JsonValue, default: T) -> T {
let i32val: i32 = json.as_i32().unwrap_or(0);
let optionval = num::FromPrimitive::from_i32(i32val);
let mut enumval: T = default;
match optionval {
Some(val) => enumval = val,
None => {}
}
return enumval;
}
The compiler complaints that:
the trait bound `T: generator::initialise::num::FromPrimitive` is not satisfied
I get the problem, but how do I solve it? I guess ideally I would tell the function that the dynamic type does in fact implement FromPrimitive (which it does)
I have a Control scene that has an HBoxContainer as a child. I want to expose its alignment property as an export variable in the parent Control node. How can I go about exporting the variable to show the correct values?
I tried export (BoxContainer.AlignMode) var alignment
But it shows as an invalid index 'AlignMode' in constant expression.
Any help?
New to Go, and coming from TypeScript.
In a `struct`, how do I give a field a string value that is one of multiple strings, in a strongly-typed manner?
type RecordStatus = `active` | `inactive` | `pending` | `fresh`
type Record = {
id string
status RecordStatus
}
How would you do that in Golang so the status field stays strongly typed, ideally avoiding a Go numeric enum?
type Record struct {
Id string
Status string // ???
}
So I discovered the use of python's ENUM class to ensure immutability of enums. This is great, and I have gone through my project converting my homemade "enum" classes to inherit from the official python ENUM classes. Yay, I'm learning.
However I also have several "constants" classes, which I had set up. But I can't seem to find any mention of python CONST classes like the ENUM classes.
So at the moment my constant classes are just classes with class variables in upper case. This makes thing clear to me, but there is always the danger of overwriting a constant without realising it.
What am I missing?
If there isn't an official CONST class in python, I would like to properly create a CONST class of my own to make sure that I don't accidentally overwrite constants in my project.
Is there a way of defining a class so that any variables declared in that class are made immutable?
I have an enum like this
enum Fruit {
Apple = 1,
Pear = 2,
}
I am receiving the values through a json, as a i32 type. How would I convert the i32 to the enum so I can match them?
let f:i32 = json['value']
// cast?
match f {
Fruit::Apple => {}
Fruit::Pear => {}
}
How would I do this without a 'transformation' function? (I have 50+ of these enums so I don't want a manual approach)
Hi, I am trying to make a cross platform 3D application that uses different graphics APIs based on the platform. I have a GPUDevice class that I want to use the PIMPL approach for implemenenting API specific code into a crossplatform class. And I am trying to create a concept that will allow me to pass a value of a specific Enum into the GPUDevice class so when it is constructed it can create a pointer to the correct API implementation as follows:
...
enum class API
{
Vulkan,
DX12,
Metal
};
template</* parameters */>
concept APIType = // concept code to check if value given is in API
template<APIType T>
class GPUDevice
{
public:
GPUDevice()
{
switch(T)
{
case(API::Vulkan)
{
api_implemenation = new VulkanImp;
}
...
}
}
private:
APIImp* api_implementation = nullptr;
};
So far everything I have tried has either led to errors with the definition of the class or errors when trying to instantiate a class with an enum value. I'm hoping someone with a better understanding of the C++ Concepts libary can help me out here.
Thanks
Version 3.4 stable
Ok..I have the following enum
enum Skill_Tag {ManaBolt,FireBolt,SummonUndead,IceSpike}
Above enum is stored in a autoloaded file call Skill
Then I have a new scene. Main node is a 2D node which I called it Container. Under Container, there 4 other 2D node. Each 2d node has a script attach to it.
And the code in the script are as follows :
export (Skill.Skill_Tag) var skill_tag
func get_skill_tag():
return skill_tag
In the Container, I also created a script and the code are as follows :
func get_skill(a_tag):
var all : Array = get_children()
var result
for i in all.size():
if all[i].get_skill_tag() == a_tag:
result = all[i]
return result
but when I called it, I am getting this error
Invalid operands 'int' and 'String' in operator ==
which got me confused, since I never converted anything to String. And when I check thru the code. I found that it is from the get_skill_tag() function. Apparently it returns skill_tag variable as string. Am I doing something wrong here?
I know I probably did something stupid, any help is appreciated
If there is a clean way to do this that isn't super hacky, or as hacky as repeating the same code over again for each enum class that I want to inherit from the base one, let me know.
I'm looking for a macro that can help me to match the Enum branches in a more readable way.
pub enum DummyType{
Type1,
Type2,
Type3,
Type24,
Type25,
}
pub fn check_side(dt:DummyType)->Side{
match dt{
DummyType::Type1 | DummyType::Type2 | DummyType::Type3 => Side:Left,
DummyType::Type24 | DummyType::Type25 => Side::Right
}
}
pub fn check_link(dt:DummyType)->Link{
match dt{
DummyType::Type1 | DummyType::Type2 => Link:Direct,
DummyType::Type3 | DummyType::Type24 | DummyType::Type25 => Link::Indircct
}
}
expecting to have a macro with a name like `select_type`, then I can convert the above code to:
pub fn check_side(dt:DummyType)->Side{
match dt{
select_type!(1,2,3) => Side::Left,
select_type!(24,25) => Side::Right
}
}
pub fn check_link(dt:DummyType)->Link{
match dt{
select_type!(1,2) => Link::Direct,
select_type!(3,24,25) => Link::Indircct
}
}
My enum has about 30 branches with the same naming pattern.
Thanks in advance.
Hello, I have writted a struct used to decoding geojson data. The decoding looks like it parses the json correctly but XCode doesn't seem to understand which type the decoded coordinates enum have.
The coordinate prop is nested differently deep depending on if it is a polygon or a multipolygon type which is why I use the enum decodable.
Can anyone tell me what I've missed or if I should approach this a different way?
https://preview.redd.it/az4h9btqia881.png?width=1662&format=png&auto=webp&s=276fcb6815785668d8d364bcdffa90f2935b25d7
Result of printing coordinate, which matches what I expect it to be.
Thanks!
I want to create a simple UI library and I want to use a Message system, where I can create a input-field with a custom Message that is created outside of the library
somehow like this:
enum Message {
Input(String)
}
let input: Input<Message> = Input::new(
/* fields */
).message(Message::Input);
Later I request this Message from the application and update the field of input accordingly.
I think I could get It working by creating a trait with the function from_string
that returns it's object with the string in it's field.
But the problem is that the user would have to manually implement this trait for his own message enum, via a very repetitive matching of every field.
iced-rs does this exactly how I want, but I do not know how they achieved this. example in iced with input-field
Is there any better way of doing this without the need of completely redesigning my library?
Itβs likely that PHP-FIG will add a recommendation to their coding guidelines, but until those guidelines are updated, do you plan to use PascalCase, camelCase or UPPER_SNAKE_CASE for your enum case naming convention?
Hi,
I am using Postgres with Sequelize for JS.
And there is a bug with using Enums that way.
A workaround is to manually check on insertion and updates that the value is inside the enum list (trough JS).
But then the type on the db will actually be a string (varchar).
Are there any disadvantages to using this method?
Here is the workaround - https://github.com/sequelize/sequelize/issues/7649#issuecomment-948966712
I was deleting a single asset and the engine crashed for whatever reason. I start it up again, I didn't lose anything at all. And the blueprint just doesn't work anymore.
Basically I'm importing an asset using a path that I write using custom enums, and it seems that those enums just... don't work? If I imput the path by hand, everything works. I print the path to the screen, the one I've created using enums, it's IDENTICAL like the one I input by hand. But it just stopped working. It worked before crash. Now it doesn't.
I've just finished working on something that took me 3 whole days and it stops working for no reason whatsoever. I'm so done.
EDIT
Reimporting relevant assets fixed the issue. I'm going to sleep.
Whenever I want to create a number of things for a specific set of objects often times tutorials and my natural habit will lead me towards creating a set of enums for an overarching "type" to use for pre-runtime code and "static" references to the data type, then pass those enums into the objects at runtime and check the object for the enum type down the road. This is awkward though a little because it means keeping two data sets ultimately, one is the enums and the other the runtime object initialization. Its not a huge deal but I cant help but think someone has found a smarter way to handle this. Any thoughts?
To be clear this is the basic concept of what I am trying to avoid:
public enum AnimalType {Cat, Dog, Fox, Lion};
Run(){
DogObject = new Animal(
AnimalType.Dog
);
FoxObject = new Animal(
AnimalType.Fox
);
etc
}
Usually the answer to this kind of thing is polymorphism, but if I need to reference a Dog in pre-runtime code I need a concrete way of referencing the Dog. I suppose one answer is still use subclasses for each current enum and then use typeof ahead of time, but that also seems unneeded since my actual use cases are oftentimes identical in terms of internal code within the objects its just keeping the different types separate that is important. Thanks!
We could have a very widely-used enum across our project, from time to time. For me, it is an AST type that many of my functions analyze.
Now I want to refactor the enum to a different layout. I suddenly found that I have to change all code that matches against the enum. I am at a loss. I don't know what to do. All I can think of is a shotgun change everywhere.
A wildcard solves part of the problems, but not all, since it only guards against adding new variants, not modifications to existing ones.
What I wish to have is something like a "wrapper match", that serve as an encapsulation so that I can change the internals while still allowing the user code to use it "the old way".
match my_enum {
MyEnum::expression() => ...
...
}
enum MyEnum {
// Old:
Expression(Expr),
// New: E
SomeNewWrapper(NewExpression),
}
enum NewExpression {
Old(Expr),
SomethingElse(d, e),
}
impl MyEnum {
fn expression(&self) -> &Expr {
...
}
}
In generally, I am thinking of matching on "getters" instead of the real enum. I've not found many discussions on it, so probably I'm doing it the wrong way. Yet I'm experiencing real pain on changing enums. What should I do? Any help will be greatly appreciated!
I have set the language standard to C++11, so what am I doing wrong?
https://preview.redd.it/p9lyph5909881.png?width=883&format=png&auto=webp&s=17ef4046dd578fe70a9b430eefdd26085cc4d2c5
https://preview.redd.it/emk15n8909881.png?width=185&format=png&auto=webp&s=08eb338ac440f15209fdf224d367af5ce5f9ca29
Please note that this site uses cookies to personalise content and adverts, to provide social media features, and to analyse web traffic. Click here for more information.