2017-12-20 21 views
0

[] 연산자를 사용할 수있는 클래스를 사용할 수있는 함수를 만들려고합니다. 나는 그것을 받아 들일 수 있도록하고 싶습니다 :인덱싱 가능한 데이터 형식을 인수로 받아들이는 함수

  1. 벡터 또는 일부 내가 찾은 실험에 의해

를 인덱싱 할 수있는 다른 컨테이너 참조하거나 값을 기준으로 하나

  • 배열 PartialOrd, PartialEq과 같은 다른 특성이 필요합니다. 또한 얼마나 많은 객체가 컨테이너에 있는지 알아야합니다. 그것은 이러한 오류를 생산

    use std::ops::Index; 
    use std::iter::ExactSizeIterator; 
    use std::cmp::PartialEq; 
    
    pub fn find<'a, I>(input: I, key: <I as std::ops::Index<u32>>::Output) -> Option<u32> 
    where 
        I: Index<u32> + ExactSizeIterator, 
        <I as std::ops::Index<u32>>::Output: PartialEq + std::marker::Sized + std::cmp::PartialOrd, 
    { 
        if input.len() == 0 { 
         return None; 
        } 
        if key < input[0] || key > input[(input.len() - 1) as u32] { 
         return None; 
        } 
        let mut index: u32 = (input.len() - 1) as u32; 
        loop { 
         if key < input[index] { 
          index /= 2; 
          continue; 
         } else if input[index] < key && input[index + 1] > key { 
          return None; 
         } else if key > input[index] { 
          index += index/2; 
          continue; 
         } else if input[index] == key { 
          return Some(index); 
         } else { 
          return None; 
         } 
        } 
    } 
    
    fn main() { 
        assert_eq!(find(&[1, 2], 2), Some(1)); 
        assert_eq!(find([1, 2], 2), Some(1)); 
        assert_eq!(find(vec![1, 2], 2), Some(1)); 
    } 
    

    :

    여기 내 코드입니다

    error[E0277]: the trait bound `&[{integer}; 2]: std::ops::Index<u32>` is not satisfied 
        --> src/main.rs:36:16 
        | 
    36 |  assert_eq!(find(&[1, 2], 2), Some(1)); 
        |    ^^^^ the type `&[{integer}; 2]` cannot be indexed by `u32` 
        | 
        = help: the trait `std::ops::Index<u32>` is not implemented for `&[{integer}; 2]` 
        = note: required by `find` 
    
    error[E0277]: the trait bound `&[{integer}; 2]: std::iter::ExactSizeIterator` is not satisfied 
        --> src/main.rs:36:16 
        | 
    36 |  assert_eq!(find(&[1, 2], 2), Some(1)); 
        |    ^^^^ the trait `std::iter::ExactSizeIterator` is not implemented for `&[{integer}; 2]` 
        | 
        = note: required by `find` 
    
    error[E0277]: the trait bound `[{integer}; 2]: std::ops::Index<u32>` is not satisfied 
        --> src/main.rs:37:16 
        | 
    37 |  assert_eq!(find([1, 2], 2), Some(1)); 
        |    ^^^^ the type `[{integer}; 2]` cannot be indexed by `u32` 
        | 
        = help: the trait `std::ops::Index<u32>` is not implemented for `[{integer}; 2]` 
        = note: required by `find` 
    
    error[E0277]: the trait bound `[{integer}; 2]: std::iter::ExactSizeIterator` is not satisfied 
        --> src/main.rs:37:16 
        | 
    37 |  assert_eq!(find([1, 2], 2), Some(1)); 
        |    ^^^^ the trait `std::iter::ExactSizeIterator` is not implemented for `[{integer}; 2]` 
        | 
        = note: required by `find` 
    
    error[E0277]: the trait bound `std::vec::Vec<{integer}>: std::ops::Index<u32>` is not satisfied 
        --> src/main.rs:38:16 
        | 
    38 |  assert_eq!(find(vec![1, 2], 2), Some(1)); 
        |    ^^^^ the type `std::vec::Vec<{integer}>` cannot be indexed by `u32` 
        | 
        = help: the trait `std::ops::Index<u32>` is not implemented for `std::vec::Vec<{integer}>` 
        = note: required by `find` 
    
    error[E0277]: the trait bound `std::vec::Vec<{integer}>: std::iter::ExactSizeIterator` is not satisfied 
        --> src/main.rs:38:16 
        | 
    38 |  assert_eq!(find(vec![1, 2], 2), Some(1)); 
        |    ^^^^ the trait `std::iter::ExactSizeIterator` is not implemented for `std::vec::Vec<{integer}>` 
        | 
        = note: required by `find` 
    
  • +0

    컴파일 오류가 없지만 위의 예와 같이 실행하십시오. [6,7,8,3] 또는 [1,2,3,4,8] 인수로 전화하려고 시도하십시오. –

    +0

    적절한 [MCVE]를 작성하십시오. [Rust Playground] (https://play.rust-lang.org)에서 정확한 문제를 재현하는 것이 좋습니다. –

    +0

    오류 텍스트를 읽고 왜 컴파일러가 잘못되었다고 생각하는지 알려주는 것이 좋습니다. 예를 들어 무언가가 구현되지 않았다는 것을 알려주는 경우 왜 그렇다고 생각합니까? 그렇지 않으면 오류 메시지를 고의로 무시하는 것처럼 보입니다. – Shepmaster

    답변

    0

    내가 그것을 구현하는 방법을 발견하지만 일부 제한 사항.

    pub struct Validator { 
        data: Vec<i32>, 
    } 
    impl<'a> From<&'a [i32; 2]> for Validator { 
        fn from(input: &'a [i32; 2]) -> Self { 
         Validator { 
          data: input.iter().map(|c| *c).collect(), 
         } 
        } 
    } 
    impl From<[i32; 2]> for Validator { 
        fn from(input: [i32; 2]) -> Self { 
         Validator { 
          data: input.iter().map(|c| *c).collect(), 
         } 
        } 
    } 
    impl From<Vec<i32>> for Validator { 
        fn from(input: Vec<i32>) -> Self { 
         Validator { data: input } 
        } 
    } 
    
    pub fn find<T>(input: T, key: i32) -> Option<usize> 
    where 
        T: std::convert::Into<Validator>, 
        Validator: std::convert::From<T>, 
    { 
        let input: Vec<i32> = input.into().data; 
    
        if input.len() == 0 { 
         return None; 
        } 
        if key < input[0] || key > input[(input.len() - 1)] { 
         return None; 
        } 
        let mut index = input.len() - 1; 
        loop { 
         if key < input[index] { 
          index /= 2; 
          continue; 
         } else if input[index] < key && input[index + 1] > key { 
          return None; 
         } else if key > input[index] { 
          index += index/2; 
          continue; 
         } else if input[index] == key { 
          return Some(index); 
         } else { 
          return None; 
         } 
        } 
    } 
    
    fn main() { 
        assert_eq!(find(&[1, 2], 2), Some(1)); 
        assert_eq!(find([1, 2], 2), Some(1)); 
        assert_eq!(find(vec![1, 2], 2), Some(1)); 
    } 
    

    당신이 각 요소 번호를 구현해야합니다 세 이상의 숫자의 배열을 받아들이는 기능이 필요합니다. 유효성 검사기 구조체 및 지원하려는 유형에 대해 Into 특성을 구현하여 VecDeque 또는 사용자 정의 구조체와 같은 더 많은 구조체에 대한 지원을 추가 할 수 있습니다.