Idea: Option over value


#1

This came up while I was playing around with parsing, that I wanted to have something that is roughly equivalent to the statement “FooBar or nothing”. Where FooBar could be a string or an i32 or something.

For my case I made a one element enumeration and then option-ed it because I wanted the option semantics but that felt clunky. And if I wanted it to be a specific value say a string this would be even weirder because I would then have to write a value function.

Is this something that others have wanted to do in the past or does it smell bad?


#2

Why did you make the one-element enumeration? Did you want a newtype pattern instead (struct FooBar(String);)? Why didn’t you just Option the inner type?

I don’t really get what you’re going at here.

(That said, parsing in Rust tends to use a lot of very specific types, lots of nested Results and Options, and code generation (macros) to clean up repetition. We tend to be correctness-focused and near overdosed on zero cost abstractions sometimes.)


#3

This sounds like Option<FooBar> to me.


#4

No I meant: the string “FooBar” or nothing. Not any arbitrary string

Sebastian Malton


#5

In serde, I usually do this as follows:

#[derive(Deserialize)]
enum FooBar {
    FooBar
}

Now you can use Option<FooBar>.


#6

Yeah, that is basically what I ended up doing. So maybe it is a thing just used in parsing but it does seem rather verbose.

Sebastian Malton


#7

Another thing you’ll see is unit structs struct FooBar;.

Depending on the exact ast semantics it might also make sense to just have a bool for “does this context have a FooBar in it”.

You’ll notice though that in more involved parsing cases that a lot of the “stateless” parse units go away though, as you’ll want to track what spans your parse comes from in order to present errors pointing back at the source location, so everything will have some state to it.