Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting size of an array passed in as an argument

Tags:

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.

like image 596
Steve Avatar asked May 06 '15 15:05

Steve


People also ask

How do you get the size of an array passed to a function?

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.

How do I get the size of an array passed to a function in C++?

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.

How do I get the size of an array?

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 do I get the size of an array parameter in C++?

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.


1 Answers

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.

like image 120
Vladimir Matveev Avatar answered Nov 09 '22 08:11

Vladimir Matveev