Rust: "Arrays, Vectors, and Slices" section should explain how to make an empty literal array

Created on 15 May 2015  路  7Comments  路  Source: rust-lang/rust

Reference: http://doc.rust-lang.org/1.0.0-beta/book/arrays-vectors-and-slices.html

For example, how would someone use an empty array in a context like this:
assert_eq!(something, []) // not enough type information
assert_eq!(something, [] : [&str; 0] ) // compiler error at ":"
assert_eq!(something, [] as [&str; 0] ) // illegal typecast

Most helpful comment

I have a counterexample when this does not work (1.26.2 stable):

assert_eq!(vec!["a"], ["a"]); // works fine
assert_eq!(<Vec<&str>>::new(), []); // error[E0282]

All 7 comments

Empty arrays aren't really useful, because they can't be filled with anything. In what cases are you matching against an empty array?

I was writing unit tests and wanted to test that my code worked with an empty array.

This code just works (1.2 nightly):

fn main() {
    let something: [i32;0] = [];
    assert_eq!(something, []);
}

(but you can't compare to [] if something is not an empty array: they're two different types.)
So I think this can be closed with not an issue.

Agreed with @liigo .

I have a counterexample when this does not work (1.26.2 stable):

assert_eq!(vec!["a"], ["a"]); // works fine
assert_eq!(<Vec<&str>>::new(), []); // error[E0282]

I ran into this while trying to write a test:

fn assert_slice_eq(actual: &[&str]) {
    assert_eq!(&[], actual)
}

tells me:

2 |     assert_eq!(&[], actual)
  |     ^^^^^^^^^^^^^^^^^^^^^^^ cannot infer type

If there is a way to write this type annotation without an extra line const empty: &[&str] = &[];, it's hard to discover.

EDIT: Sorry I did not see that this issue was closed before commenting.

@kosta in general, questions are best asked on users.rust-lang.org

Was this page helpful?
0 / 5 - 0 ratings

Related issues

withoutboats picture withoutboats  路  213Comments

thestinger picture thestinger  路  234Comments

nikomatsakis picture nikomatsakis  路  268Comments

nikomatsakis picture nikomatsakis  路  236Comments

aturon picture aturon  路  417Comments