I can't seem to make this work. I keep getting an error saying 'len' doesn't exist on type '&[String]'.
fn testLength(arr: &[String]) { if arr.len >= 10 { // Do stuff } }
I'm still pretty new to Rust, and I understand this is a pointer to a raw string somewhere. Why can't I get the length of the underlying string at runtime? Googling things like "length of string in rust" and "length of array in rust" lead me absolutely no where.
The reason is, arrays are always passed pointers in functions, i.e., findSize(int arr[]) and findSize(int *arr) mean exactly same thing. Therefore the cout statement inside findSize() prints the size of a pointer.
Using sizeof() function to Find Array Length in C++ The sizeof() operator in C++ returns the size of the passed variable or data in bytes. Similarly, it returns the total number of bytes required to store an array too.
We can find the size of an array using the sizeof() operator as shown: // Finds size of arr[] and stores in 'size' int size = sizeof(arr)/sizeof(arr[0]);
How to print size of array parameter in a function in C++? The size of a data type can be obtained using sizeof(). A program that demonstrates the printing of the array parameter in a function in C++ is given as follows.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With