Is_alphabetic for strings

char has a method called is_alphabetic (and many other similar ones).
I'd like to check if all the characters of a string are alphabetic.

Would this be the recommended way to check it?

let text = "hello".to_string();
text.chars().all(|chr| chr.is_alphabetic())

The closure is unnecessary.

1 Like

Nice! What is this construct called and can it be used if I have multiple conditions? e.g. alphanumeric || space

What construct? I am simply designating the function by its name. There's no separate language construct involved.

If you write a function that performs that check, you can just use of the name of that function, too. The point is, if you already have such a function, then don't make an unnecessary closure. If you don't, then do make an inline closure (unless you need it to reuse it multiple times).

1 Like

A method on some type, T, is just a function which takes T as the first argument, so chr.is_alphabetic() is just shorthand ("syntactic sugar"0 for char::is_alphabetic(chr).

That means char::is_alphabetic is just a normal function that you can pass around.


Oh, I see, so char::is_alphabetic is a function. Thanks for pointing it out!

Oh, that was not clear to me from the syntax. Thanks.

It's the same for every item, simply a path. crate::module::submodule::item. Or, since char is a primitive, it's immediately in scope, and the type itself is the namespace for its methods. Nothing special.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.