Why doesn't rust narrow enums after an "if let"

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?

πŸ‘︎ 39
πŸ’¬︎
πŸ‘€︎ u/GeeWengel
πŸ“…︎ Jan 21 2022
🚨︎ report
im pretty sure Enum for this doesn't even work
πŸ‘︎ 110
πŸ’¬︎
πŸ‘€︎ u/TinyAnchor
πŸ“…︎ Jan 17 2022
🚨︎ report
Blatt 2: Monat kein Enum (-1P), Blatt 3: v.redd.it/ucu9mwzweq681
πŸ‘︎ 281
πŸ’¬︎
πŸ‘€︎ u/_s3vro
πŸ“…︎ Dec 20 2021
🚨︎ report
A Question on Enums

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

πŸ‘︎ 4
πŸ’¬︎
πŸ‘€︎ u/GaiaPagan
πŸ“…︎ Jan 12 2022
🚨︎ report
Converting enum from/to strings when reading/writing to file

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

πŸ‘︎ 6
πŸ’¬︎
πŸ“…︎ Jan 22 2022
🚨︎ report
API method fails as it's trying to convert an enum into an array

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?

πŸ‘︎ 9
πŸ’¬︎
πŸ“…︎ Jan 11 2022
🚨︎ report
Constraints Aren't Enums zephyrtronium.github.io/a…
πŸ‘︎ 38
πŸ’¬︎
πŸ‘€︎ u/zephyrtronium
πŸ“…︎ Dec 20 2021
🚨︎ report
How to get the name of an enum in C#

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

πŸ‘︎ 4
πŸ’¬︎
πŸ“…︎ Jan 09 2022
🚨︎ report
are enum good for performance?

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?

πŸ‘︎ 27
πŸ’¬︎
πŸ‘€︎ u/Deralser
πŸ“…︎ Dec 13 2021
🚨︎ report
Find the number of Elements in an `enum`

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) -&gt; usize {
        match items {
            Focus::block1 =&gt; 0,
            Focus::block2 =&gt; 1,
            Focus::block3 =&gt; 2,
        }
    }
    fn from_usize(items: usize) -&gt; Focus {
        match items {
            0 =&gt; Focus::block1,
            1 =&gt; Focus::block2,
            2 =&gt; Focus::block3,
            _ =&gt; {}
        }
    }
}

struct App {
    current_focus: Focus,
}

impl App {
    fn new() -&gt; Self {
        Self { current_focus: Focus::block1 }    
    }
    fn next(&amp;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 ➑

πŸ‘︎ 10
πŸ’¬︎
πŸ‘€︎ u/DexterInAI
πŸ“…︎ Dec 16 2021
🚨︎ report
Enums in Go: best way to convert back to string value?

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?

πŸ‘︎ 10
πŸ’¬︎
πŸ‘€︎ u/otomoxd
πŸ“…︎ Jan 06 2022
🚨︎ report
Unscripted C# - Deck of Cards (Classes, Enums and Lists)

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

πŸ‘︎ 12
πŸ’¬︎
πŸ‘€︎ u/edgeofsanity76
πŸ“…︎ Jan 12 2022
🚨︎ report
Tabled [v0.4.0] - An easy to use library for pretty print tables of Rust structs and enums.

https://github.com/zhiburt/tabled

There is a list of main additions.

  • Highlight modifier which does highlight of any combination of cells.
  • Concat modifier which does concatenation of two tables into one.
  • TableIteratorExt trait which can be used to create table from `Iterator`.

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 β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”΄β”€β”€β”€β”΄β”€β”€β”€β”˜
πŸ‘︎ 32
πŸ’¬︎
πŸ‘€︎ u/zhiburt
πŸ“…︎ Dec 30 2021
🚨︎ report
New Release: Doctrine ORM 2.11 with Enums, Virtual Columns, Read-Only Properties, Nested Attributes and more doctrine-project.org/2022…
πŸ‘︎ 98
πŸ’¬︎
πŸ‘€︎ u/tigitz
πŸ“…︎ Jan 13 2022
🚨︎ report
Can I mix names between enum namespace and primitive typedef?

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, &amp;stream);
πŸ‘︎ 4
πŸ’¬︎
πŸ‘€︎ u/Kyr333
πŸ“…︎ Jan 13 2022
🚨︎ report
How can I change state of this enum from another script?
πŸ‘︎ 5
πŸ’¬︎
πŸ‘€︎ u/asdasfadamas
πŸ“…︎ Jan 09 2022
🚨︎ report
extending enums

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?)

πŸ‘︎ 15
πŸ’¬︎
πŸ‘€︎ u/joserenau
πŸ“…︎ Dec 19 2021
🚨︎ report
How do I pull an enum value from a different class into an if statement for a maze

[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 &lt; size; i++)    
 {         
        for (int j = 0; j &lt; 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); 
}
πŸ‘︎ 5
πŸ’¬︎
πŸ‘€︎ u/WhiskeyJoes
πŸ“…︎ Jan 03 2022
🚨︎ report
Enum.dedup_by is removing all consecutive duplicates when I expect it to only remove elements that return true based on the criteria given buy the passes in function.
Enum.dedup_by([ "a", 'foo', 1, "b", 7, 4, "c", "d"], fn x -&gt;  is_integer(x) end ) |&gt; 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?

πŸ‘︎ 8
πŸ’¬︎
πŸ‘€︎ u/elfcup_mayhem
πŸ“…︎ Jan 22 2022
🚨︎ report
Possible to Export Enum Index Naming With Array?

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?

πŸ‘︎ 10
πŸ’¬︎
πŸ‘€︎ u/Jahmann
πŸ“…︎ Jan 16 2022
🚨︎ report
Unscripted C# - Deck of Cards (Classes, Enums and Lists) - All my videos will be unscripted, so you see the mistakes I make and how I go about fixing them, as well as my thought processes. I hope it helps anyone. youtu.be/3Ga-wrXZLHc
πŸ‘︎ 6
πŸ’¬︎
πŸ‘€︎ u/edgeofsanity76
πŸ“…︎ Jan 12 2022
🚨︎ report
Best way to print the name of an unnamed enum's constants?

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?

πŸ‘︎ 7
πŸ’¬︎
πŸ‘€︎ u/carllacan
πŸ“…︎ Jan 05 2022
🚨︎ report
inspect enum variant size differences?

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)

πŸ‘︎ 6
πŸ’¬︎
πŸ‘€︎ u/padraig_oh
πŸ“…︎ Jan 17 2022
🚨︎ report
is Enum costly?

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

πŸ‘︎ 4
πŸ’¬︎
πŸ‘€︎ u/glitterpyjamas
πŸ“…︎ Jan 13 2022
🚨︎ report
converting a json value to an enum in a generic way

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&lt;T&gt;(json: &amp;JsonValue, default: T) -&gt; 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) =&gt; enumval = val, 
        None =&gt; {} 
    }
    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)

πŸ‘︎ 5
πŸ’¬︎
πŸ‘€︎ u/garma87
πŸ“…︎ Jan 07 2022
🚨︎ report
Design Rails enums the right way - avoid data integrity problems longliveruby.com/articles…
πŸ‘︎ 27
πŸ’¬︎
πŸ‘€︎ u/pdabrowski
πŸ“…︎ Jan 11 2022
🚨︎ report
How to export built-in enums from other classes?

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?

πŸ‘︎ 2
πŸ’¬︎
πŸ‘€︎ u/_bhgt_
πŸ“…︎ Jan 21 2022
🚨︎ report
How to Use Enums in Rails blog.saeloun.com/2022/01/…
πŸ‘︎ 5
πŸ’¬︎
πŸ‘€︎ u/chetansgawai
πŸ“…︎ Jan 05 2022
🚨︎ report
How to type a string literal union (or a string enum) in Go?

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 // ???
}
πŸ‘︎ 20
πŸ’¬︎
πŸ‘€︎ u/NotJustSagacity
πŸ“…︎ Dec 24 2021
🚨︎ report
If there is an enum class why doesn't there appear to be any constant classes

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?

πŸ‘︎ 6
πŸ’¬︎
πŸ‘€︎ u/CarpeCol
πŸ“…︎ Jan 17 2022
🚨︎ report
Casting i32 to enums

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 =&gt; {}

Fruit::Pear =&gt; {}

}

How would I do this without a 'transformation' function? (I have 50+ of these enums so I don't want a manual approach)

πŸ‘︎ 7
πŸ’¬︎
πŸ‘€︎ u/garma87
πŸ“…︎ Jan 06 2022
🚨︎ report
Help with C++20 Concepts and Enums

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&lt;/* parameters */&gt;
    concept APIType = // concept code to check if value given is in API

template&lt;APIType T&gt;
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

πŸ‘︎ 3
πŸ’¬︎
πŸ‘€︎ u/BattleFrogue
πŸ“…︎ Jan 08 2022
🚨︎ report
Enum problem ...again...

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

πŸ‘︎ 6
πŸ’¬︎
πŸ‘€︎ u/lowpolygon
πŸ“…︎ Dec 24 2021
🚨︎ report
Best way to inherit enum classes

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.

πŸ‘︎ 5
πŸ’¬︎
πŸ‘€︎ u/cheeseDickies
πŸ“…︎ Dec 17 2021
🚨︎ report
Rust Macro to generate Enum matching

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)-&gt;Side{
  match dt{
    DummyType::Type1 | DummyType::Type2 | DummyType::Type3 =&gt; Side:Left,
    DummyType::Type24 | DummyType::Type25 =&gt; Side::Right
  }
}


pub fn check_link(dt:DummyType)-&gt;Link{
  match dt{
    DummyType::Type1 | DummyType::Type2 =&gt; Link:Direct,
    DummyType::Type3 | DummyType::Type24 | DummyType::Type25 =&gt; 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)-&gt;Side{
  match dt{
    select_type!(1,2,3) =&gt; Side::Left,
    select_type!(24,25) =&gt; Side::Right
  }
}


pub fn check_link(dt:DummyType)-&gt;Link{
  match dt{
    select_type!(1,2) =&gt; Link::Direct,
    select_type!(3,24,25) =&gt; Link::Indircct
  }
}

My enum has about 30 branches with the same naming pattern.

Thanks in advance.

πŸ‘︎ 5
πŸ’¬︎
πŸ‘€︎ u/xudesheng
πŸ“…︎ Dec 21 2021
🚨︎ report
Issue working with decoded JSON enum types

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!

πŸ‘︎ 3
πŸ’¬︎
πŸ‘€︎ u/spunkle
πŸ“…︎ Dec 28 2021
🚨︎ report
Is it possible to pass an enum as a generic to a function that returns said enum with a String in the enum's field?

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&lt;Message&gt; = 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?

πŸ‘︎ 2
πŸ’¬︎
πŸ‘€︎ u/Bruno_Wallner
πŸ“…︎ Jan 04 2022
🚨︎ report
What is the enum naming convention you plan to use?

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?

View Poll

πŸ‘︎ 19
πŸ’¬︎
πŸ‘€︎ u/Bb8natw
πŸ“…︎ Nov 24 2021
🚨︎ report
Are there benefits to use Enum over String when it comes to performence? (Postgres)

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

πŸ‘︎ 4
πŸ’¬︎
πŸ‘€︎ u/xSypRo
πŸ“…︎ Dec 20 2021
🚨︎ report
After a crash, blueprint (enums?) just stopped working correctly

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.

πŸ‘︎ 2
πŸ’¬︎
πŸ‘€︎ u/dejvidBejlej
πŸ“…︎ Jan 14 2022
🚨︎ report
Is there a cleaner alternative than enum type + runtime object pairs?

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!

πŸ‘︎ 7
πŸ’¬︎
πŸ‘€︎ u/AluminiumCaffeine
πŸ“…︎ Dec 04 2021
🚨︎ report
How to Handle Refactoring with Enums?

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() =&gt; ...
    ...
}

enum MyEnum {
    // Old:
    Expression(Expr),
    // New: E
    SomeNewWrapper(NewExpression),
}

enum NewExpression {
    Old(Expr),
    SomethingElse(d, e),
}

impl MyEnum {
    fn expression(&amp;self) -&gt; &amp;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!

πŸ‘︎ 4
πŸ’¬︎
πŸ‘€︎ u/Seideun
πŸ“…︎ Dec 20 2021
🚨︎ report
Back after a long hiatus: Let's Build a 2D Platformer Part 18!: Finite State Machine, Running, Enums, Match Statements, the Ternary Operator. This tutorial sets up the player's code for future tutorials: wall jumps & ladders. πŸ’™πŸ€– youtu.be/HMvnMmwJ0sk
πŸ‘︎ 9
πŸ’¬︎
πŸ‘€︎ u/BornCG
πŸ“…︎ Jan 09 2022
🚨︎ report
New Release: Doctrine ORM 2.11 with Enums, Virtual Columns, Read-Only Properties, Nested Attributes and more (/r/PHP) doctrine-project.org/2022…
πŸ‘︎ 3
πŸ’¬︎
πŸ‘€︎ u/ContentForager2
πŸ“…︎ Jan 19 2022
🚨︎ report
Why doesn't Clion 2019.3 allow for enum forward declaration

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

πŸ‘︎ 5
πŸ’¬︎
πŸ‘€︎ u/qH0enix
πŸ“…︎ Dec 28 2021
🚨︎ report

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.