Specify params for function

I want to ensure that only some types can be the param of the function.
Here is how I implement it now.

// assume that only char and String a valid to be the param
trait Marker1 {}
impl Marker1 for char {}
impl Marker1 for String {}
fn funtion(param1 : impl Marker1) {
         //--snip--
}

I don't think it is a smart way to do it,especially in big projects.
Any ideas to optimize?

Normally I would just accept an enum with precisely the types I want to accept.

2 Likes

You could use a sealed trait.

If it's really just a small number of variants, you could take an enum.

Edit: to elaborate the second point a bit more, your enum could implement From<V> for the types V it contains, and your function could take T: Into<TheEnum>.

2 Likes

Is this a stable feature?
I didn't see the feature gate in the example

Yes, it's part of how the privacy system works and is used intentionally in the wild and in stdlib.

1 Like

Thanks

Well,I didn't get how sealed trait works
I've looked at the example,The base trait needs to do some work.But mine doesn't.It is just a marker.

If you want to use the trait approach, then the trait always have to do some work. If you don't want to make it functional, just ditch the trait approach entirely and use the enum.

Oh I get it,sorry for disturbing

When you have a generic function, the only way you can make use of the generic types inside of the function are via the trait bounds of that function. The function can't "tell" what the original types was by design, and has to make sense (compile) for any type that meets the bounds. This way, if it compiles, you know it can be monomorphized (called) with any type that meets the bounds.

I.e. it's not a type-blind macro system. (Contrast with C++ templates, which might or might not error depending on what types you feed them.)

2 Likes

The very purpose of traits is to confer a common set of operations/capabilities on a set of types so that those types can be used uniformly, i.e. in generic contexts. What leads you to believe this is not the/a good way to do what you are trying to do?