Getting size of an array passed in as an argument
Of course, you can do it - it's just len
is not a field, it's a method:
fn test_length(arr: &[String]){ if arr.len() >= 10 { // Do stuff }}
If you only started learning Rust, you should read through the official book - you will also find why &[str]
does not make sense (in short, str
is unsized type, and you can't make an array of it; instead &str
should be used for borrowed strings and String
for owned strings; most likely you have a Vec<String>
somewhere, and you can easily get &[String]
out of it).
I would also add that it is not clear if you want to pass a string or an array of strings into the function. If it is a string, then you should write
fn test_length(arr: &str) { if arr.len() >= 10 { // Do stuff }}
len()
on a string, however, returns the length in bytes which may be not what you need (length in bytes != length in "characters" in general, whatever definition of "character" you use, because strings are in UTF-8 in Rust, and UTF-8 is a variable width encoding).
Note that I also changed testLength
to test_length
because snake_case is the accepted convention for Rust programs.