Getting the size of the array passed as an argument

I can't get this to work. I get an error stating that "len" does not exist for type "& [String]".

fn testLength(arr: &[String]) { if arr.len >= 10 { // Do stuff } } 

I'm still pretty new to Rust, and I understand that this is a pointer to a raw string somewhere. Why can't I get the length of the base string at runtime? Things like “string length in rust” and “array length in rust” don't lead me at all.

+19
source share
1 answer

Of course you can do this - just len not a field, this is a method:

 fn test_length(arr: &[String]){ if arr.len() >= 10 { // Do stuff } } 

If you have just started to learn Rust, you should read the official book - you will also find out why &[str] does not make sense (in short, str is notized type, and you cannot create an array of it; instead, &str should be used for borrowed lines and String for owned strings; most likely you have Vec<String> somewhere, and you can easily get &[String] from it).

I would also add that it is unclear whether you want to pass a string or an array of strings to a function. If this is a string, you should write

 fn test_length(arr: &str) { if arr.len() >= 10 { // Do stuff } } 

len() in a string, however, returns a length in bytes, which may not be what you need (length in bytes! = length in “characters” in general, regardless of the definition of “character” that you use, since strings are in UTF -8 in Rust, and UTF-8 is variable-width encoding).

Note that I also changed testLength to test_length because snake_case is an accepted convention for Rust programs.

+30
source

Source: https://habr.com/ru/post/986675/


All Articles