rust - How can I get the length of a tuple? -


this behaviour tried:

struct matrix(f32, f32, f32, f32); let matrix = matrix(1.1, 1.2, 2.1, 2.2); matrix.len();    // expected `4` 

which produces error:

error[e0599]: no method named `len` found type `&tuples::matrix` in current scope   --> src/tuples.rs:19:44    | 19 |         println!("matrix length: {}", self.len());    |                                            ^^^    |    = help: items traits can used if trait implemented , in scope    = note: following traits define item `len`, perhaps need implement 1 of them:            candidate #1: `std::iter::exactsizeiterator`            candidate #2: `core::slice::sliceext`            candidate #3: `core::str::strext` 

std::iter::exactsizeiterator looks candidate, still don't know how implement it

context

whilst trying reverse matrix, realized instead of dryly listing reverse indexes of matrix so:

fn reverse(matrix: matrix) -> matrix {     return matrix(matrix.3, matrix.2, matrix.1, matrix.0) } 

i perhaps iterate on matrix in reverse order. saw how iterate or map on tuples? , thought complex. if 1 able length of tuple, 1 solve question "how iterate or map on tuples?" simpler solution. obviously, use '4' length, if weren't using struct rather tuple of unknown length.

there few ways approach question. i'll try expand go.

matrix.len();    // expected `4` 

you've defined own matrix datatype. no additional logic, it's entirely define this, e.g.

impl matrix {     fn len(&self) -> usize {         4     } } 

personally think reverse function fine as-is, because it's important balance dry readability, , differentiate repetition of code repetition of logic.

the other piece here having length on own doesn't offer here. matrix.0 explicit syntax in rust, there's no way use length that. matrix[i] not operation have implemented on datatype. can potentially implement or iterator type, doesn't seem you'd want here. iterator stream of consistent items, matrix items have explicit meaning based on indices kind of lose meaning in context of iterator.

i'll add can trim down reverse using destructuring assignment , auto-return, via

fn reverse(matrix: matrix) -> matrix {     let matrix(a, b, c, d) = matrix;     matrix(d, c, b, a) } 

Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -