#Is generic the right tool to use on functions with different function bodies?

17 messages · Page 1 of 1 (latest)

bitter skiff
#

Generics isn't going to help you there besides using something like the TryFrom trait, once that you've found the bounds of the number you're parsing.

#

Generics is about grouping types in sets according to some properties, and writing a function that acts on said properties just once, but your types don't have anything in common that you can abstract between those two functions.

sand olive
#

In this case would I just leave it as is?

#

I was thinking maybe there's a way to clean up the function call, e.g.
convert::<64>(some_bytes)

bitter skiff
#

TryFrom<[u8]> might be implemented for f64 and u64, let me look at the docs

sand olive
#

I can't exactly use try_from() since the bytes are of utf8 strings

bitter skiff
#

Doesn't seem like. If you had a &str you can use parse

#

There's also the crate lexical to lex numbers partially

sand olive
#

I have my own algorithm to do the conversion, it's just I was hoping I can have a clean function signature

bitter skiff
#

I think that's pretty concise already. If your bytes are utf8 you can use &str and &str methods with it. &[u8] for parsing is used when all bytes are ascii so you don't spend time computing the byte lengths of each character.

#

just to have the information complete.

sand olive
#

thanks. I actually benchmarked parse, my algorithm is quite a bit faster

#

(due to very specific use case)

bitter skiff
#

But TL;DR I see no point on using generics, since your function signatures are pretty simple and doesn't look like you could use this in many different ways

#

Feel free to experiment though, maybe you want to abstract over the stream or sth