Getting size of an array passed in as an argument

26,473

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.

Share:
26,473

Related videos on Youtube

Steve
Author by

Steve

Updated on August 26, 2020

Comments

  • Steve
    Steve over 3 years

    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.

  • Steve
    Steve about 9 years
    So I wouldn't use &[str] at all? What if I wanted an array of borrowed strings? Would that be [&str]?
  • Vladimir Matveev
    Vladimir Matveev about 9 years
    @Steve, yes, &[&str] is a slice of borrowed strings (not array - arrays have fixed size and their types look like [&str; 123]). &[str] is not a valid type - T in &[T] should be sized (implement Sized trait) because slices point to a sequence of elements which are laid out in the memory uniformly. This requires each element to have definite size. str has no definite size, so it does not implement Sized and can't be used in arrays. Besides, there is also no way to construct bare str.