< 返回版块

2019-05-15 11:25    责任编辑:jay

标签:Tyro,Novice,Learning

trait

-

/* It prints:
100.00000000000003 3.1622776601683795*/
fn main() {
    fn quartic_root(x: f64) -> f64 { x.sqrt().sqrt() }
    let qr = quartic_root(100f64);
    print!("{} {}", qr * qr * qr * qr, qr);
}
/* It prints:
3.1622776601683795 3.1622777*/
fn main() {
    fn quartic_root_f64(x: f64) -> f64 { x.sqrt().sqrt() }
    fn quartic_root_f32(x: f32) -> f32 { x.sqrt().sqrt() }
    print!("{} {}",
        quartic_root_f64(100f64),
        quartic_root_f32(100f32));
}
// ILLEGAL
fn main() {
    fn quartic_root<Number>(x: Number) -> Number {
        x.sqrt().sqrt()
    }
    print!("{} {}",
        quartic_root(100f64),
        quartic_root(100f32));
}

cpp

/* It prints:
3.16228 3.16228*/
#include <iostream>
#include <cmath>

template <typename Number>
Number quartic_root(Number x) {
    return sqrt(sqrt(x));
}

int main() {
    std::cout << quartic_root((float)100)
        << " " << quartic_root((double)100);
}
// ILLEGAL
#include <iostream>
#include <cmath>

template <typename Number>
Number quartic_root(Number x) {
    return sqrt(sqrt(x));
}

int main() {
    std::cout << quartic_root("Hello");
}

trait

/* It prints:
3.1622776601683795 3.1622777*/
fn main() {
    trait HasSquareRoot {
        fn sq_root(self) -> Self;
    }
    impl HasSquareRoot for f32 {
        fn sq_root(self) -> Self { f32::sqrt(self) }
    }
    impl HasSquareRoot for f64 {
        fn sq_root(self) -> Self { f64::sqrt(self) }
    }
    fn quartic_root<Number>(x: Number) -> Number
    where Number: HasSquareRoot {
        x.sq_root().sq_root()
    }
    print!("{} {}",
        quartic_root(100f64),
        quartic_root(100f32));
}
// It does nothing.
fn main() {
    fn _f1<T>(a: T) -> T { a }
    fn _f2<T>(a: T) -> T {
        let b: T = a;
        let mut c = b;
        c = _f1(c);
        c
    }
    fn _f3<T>(a: &T) -> &T { a }
}
// ILLEGAL
fn main() {
    fn g(a: i32) { }
    fn f<T>(a: T) -> bool {
        g(a);
        a == a
    }
}
/* It prints:
A, B; B, A*/
fn main() {
    let mut a = 'A';
    let mut b = 'B';
    print!("{}, {}; ", a, b);
    std::mem::swap(&mut a, &mut b);
    print!("{}, {}", a, b);
}

sqrt

/* It prints:
3.1622776601683795 3.1622777*/
fn main() {
    fn sqrt() {}
    trait HasSquareRoot {
        fn sqrt(self) -> Self;
    }
    impl HasSquareRoot for f32 {
        fn sqrt(self) -> Self { f32::sqrt(self) }
    }
    impl HasSquareRoot for f64 {
        fn sqrt(self) -> Self { f64::sqrt(self) }
    }
    fn quartic_root<Number>(x: Number) -> Number
    where Number: HasSquareRoot {
        x.sqrt().sqrt()
    }
    sqrt();
    print!("{} {}",
        quartic_root(100f64),
        quartic_root(100f32));
}
/* It prints:
NaN NaN*/
fn main() {
    fn sqrt() {}
    trait HasSquareRoot {
        fn sqrt(self) -> Self;
    }
    impl HasSquareRoot for f32 {
        fn sqrt(self) -> Self { f32::sqrt(self) }
    }
    impl HasSquareRoot for f64 {
        fn sqrt(self) -> Self { f64::sqrt(self) }
    }
    fn quartic_root<Number>(x: Number) -> Number
    where Number: HasSquareRoot {
        x.sqrt().sqrt()
    }
    sqrt();
    print!("{} {}",
        quartic_root(-100f64),
        quartic_root(-100f32));
}

/* It prints:
3.1622776601683795 3.1622777*/
fn main() {
    trait HasSquareRoot {
        fn sqrt(self) -> Self;
    }
    impl HasSquareRoot for f32 {
        fn sqrt(self) -> Self { f32::sqrt(self) }
    }
    impl HasSquareRoot for f64 {
        fn sqrt(self) -> Self { f64::sqrt(self) }
    }
    trait HasAbsoluteValue {
        fn abs(self) -> Self;
    }
    impl HasAbsoluteValue for f32 {
        fn abs(self) -> Self { f32::abs(self) }
    }
    impl HasAbsoluteValue for f64 {
        fn abs(self) -> Self { f64::abs(self) }
    }
    fn abs_quartic_root<Number>(x: Number) -> Number
    where Number: HasSquareRoot + HasAbsoluteValue {
        x.abs().sqrt().sqrt()
    }
    print!("{} {}",
        abs_quartic_root(-100f64),
        abs_quartic_root(-100f32));
}
/* It prints:
3.1622776601683795 3.1622777*/
fn main() {
    trait HasSquareRoot {
        fn sqrt(self) -> Self;
    }
    impl HasSquareRoot for f32 {
        fn sqrt(self) -> Self { f32::sqrt(self) }
    }
    impl HasSquareRoot for f64 {
        fn sqrt(self) -> Self { f64::sqrt(self) }
    }
    trait HasAbsoluteValue {
        fn abs(self) -> Self;
    }
    impl HasAbsoluteValue for f32 {
        fn abs(self) -> Self { f32::abs(self) }
    }
    impl HasAbsoluteValue for f64 {
        fn abs(self) -> Self { f64::abs(self) }
    }
    fn abs_quartic_root<Number>(x: Number) -> Number
    where Number: HasSquareRoot + HasAbsoluteValue {
        x.abs().sqrt().sqrt()
    }
    print!("{} {}",
        abs_quartic_root(-100f64),
        abs_quartic_root(-100f32));
}

/* It prints:
abcd,3,[7]; abcd,3,[7]*/
fn main() {
    print!("{},", "abcd".to_string());
    print!("{},", [1, 2, 3].len());
    let mut v1 = vec![0u8; 0];
    v1.push(7u8);
    print!("{:?}; ", v1);

    print!("{},", std::string::ToString::to_string("abcd"));
    print!("{:?},", <[i32]>::len(&[1, 2, 3]));
    let mut v2 = vec![0u8; 0];
    Vec::push(&mut v2, 7u8);
    print!("{:?}", v2);
}
/* It prints:
14*/
fn main() {
    fn double(x: i32) -> i32 {
        x * 2
    }
    print!("{}", double(7i32));
}
// ILLEGAL
fn main() {
    fn double(x: i32) -> i32 {
        x * 2
    }
    print!("{}", 7i32.double());
}
/* It prints:
14*/
fn main() {
    trait CanBeDoubled {
        fn double(self) -> Self;
    }
    impl CanBeDoubled for i32 {
        fn double(self) -> Self {
            self * 2
        }
    }
    print!("{}", 7i32.double());
}
// ILLEGAL
fn double(self) -> Self {
fn double(self: Self) -> Self {
fn double(self: i32) -> Self {
fn double(self) -> i32 {
fn double(self: Self) -> i32 {
fn double(self: i32) -> i32 {

LettersCount

/* It prints:
0 0 3 2 */
fn main() {
    trait LettersCount {
        fn letters_count(&self, ch: char) -> usize;
    }
    impl LettersCount for str {
        fn letters_count(&self, ch: char) -> usize {
            let mut count = 0;
            for c in self.chars() {
                if c == ch {
                    count += 1;
                }
            }
            count
        }
    }
    print!("{} ", "".letters_count('a'));
    print!("{} ", "ddd".letters_count('a'));
    print!("{} ", "ddd".letters_count('d'));
    print!("{} ", "foobarbaz".letters_count('a'));
}
/* It prints:
0 0 3 2 */
fn main() {
    trait LettersCount {
        fn letters_count(&self, ch: char) -> usize;
    }
    impl LettersCount for str {
        fn letters_count(&self, ch: char) -> usize {
            self.chars().filter(|c| *c == ch).count()
        }
    }
    print!("{} ", "".letters_count('a'));
    print!("{} ", "ddd".letters_count('a'));
    print!("{} ", "ddd".letters_count('d'));
    print!("{} ", "foobarbaz".letters_count('a'));
}

struct

/* It prints:
-2.3 + 0i, -2.1 - 5.2i, -2.2 + 5.2i*/
fn main() {
    struct Complex {
        re: f64,
        im: f64,
    }
    impl std::fmt::Display for Complex {
        fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
            write!(
                f,
                "{} {} {}i",
                self.re,
                if self.im >= 0. { '+' } else { '-' },
                self.im.abs()
            )
        }
    }
    let c1 = Complex { re: -2.3, im: 0. };
    let c2 = Complex { re: -2.1, im: -5.2 };
    let c3 = Complex { re: -2.2, im: 5.2 };
    print!("{}, {}, {}", c1, c2, c3);
}
/* It prints:
None Some(22)*/
fn main() {
    fn get_third(r: std::ops::Range<u32>) -> Option<u32> {
        if r.len() >= 3 {
            Some(r.start + 2)
        } else {
            None
        }
    }
    print!("{:?} {:?}", get_third(10..12), get_third(20..23));
}
/* It prints:
None Some(3.1)*/
fn main() {
    fn get_third(s: &[f64]) -> Option<f64> {
        if s.len() >= 3 {
            Some(s[2])
        } else {
            None
        }
    }
    print!("{:?} {:?}",
        get_third(&[1.0, 2.0]),
        get_third(&[1.1, 2.1, 3.1]));
}
// ILLEGAL
fn main() {
    fn get_third<Iter, Item>(mut iterator: Iter) -> Option<Item> {
        iterator.next();
        iterator.next();
        iterator.next()
    }
    print!("{:?} {:?}",
        get_third(0..9),
        get_third([11, 22, 33, 44].iter()));
}
// ILLEGAL
fn main() {
    fn get_third<Iter, Item>(mut iterator: Iter) -> Option<Item>
    where Iter: std::iter::Iterator {
        iterator.next();
        iterator.next();
        iterator.next()
    }
    print!("{:?} {:?}",
        get_third(0..9),
        get_third([11, 22, 33, 44].iter()));
}

/* It prints:
2.3 3.4*/
fn main() {
    fn f1(x: f32) -> f32 { x }
    fn f2(x: f32) -> f32 { x }
    let a: f32 = 2.3;
    let b: f32 = 3.4;
    print!("{} {}", f1(a), f2(b));
}
/* It prints:
2.3 3.4*/
fn main() {
    type Number = f32;
    fn f1(x: Number) -> Number { x }
    fn f2(x: Number) -> Number { x }
    let a: Number = 2.3;
    let b: Number = 3.4;
    print!("{} {}", f1(a), f2(b));
}
// It does nothing.
fn main() {
    type Number = f32;
    let a: Number = 2.3;
    let _b: f32 = a;
}

// It does nothing.
fn main() {
    trait Searchable<Key> {
        fn contains(&self, key: Key) -> bool;
    }
    fn is_present<Collection>(coll: &Collection, id: u32) -> bool
    where Collection: Searchable<u32>
    {
        coll.contains(id)
    }
}

where

/* It prints:
false true*/
fn main() {
    trait Searchable<Key> {
        fn contains(&self, key: Key) -> bool;
    }
    struct RecordWithId {
        id: u32,
        _descr: String,
    }
    struct NameSetWithId {
        data: Vec<RecordWithId>,
    }
    impl Searchable<u32> for NameSetWithId {
        fn contains(&self, key: u32) -> bool {
            for record in self.data.iter() {
                if record.id == key {
                    return true;
                }
            }
            false
        }
    }
    fn is_present<Collection>(coll: &Collection, id: u32) -> bool
    where
        Collection: Searchable<u32>,
    {
        coll.contains(id)
    }
    let names = NameSetWithId {
        data: vec![
            RecordWithId {
                id: 34,
                _descr: "John".to_string(),
            },
            RecordWithId {
                id: 49,
                _descr: "Jane".to_string(),
            },
        ],
    };
    print!("{} {}", is_present(&names, 48), is_present(&names, 49));
}
/* It prints:
0, 1; false true*/
fn main() {
    trait Searchable<Key, Count> {
        fn contains(&self, key: Key) -> bool;
        fn count(&self, key: Key) -> Count;
    }
    struct RecordWithId {
        id: u32,
        _descr: String,
    }
    struct NameSetWithId {
        data: Vec<RecordWithId>,
    }
    impl Searchable<u32, usize> for NameSetWithId {
        fn contains(&self, key: u32) -> bool {
            for record in self.data.iter() {
                if record.id == key {
                    return true;
                }
            }
            false
        }
        fn count(&self, key: u32) -> usize {
            let mut c = 0;
            for record in self.data.iter() {
                if record.id == key {
                    c += 1;
                }
            }
            c
        }
    }
    fn is_present<Collection>(coll: &Collection, id: u32) -> bool
    where
        Collection: Searchable<u32, usize>,
    {
        coll.contains(id)
    }
    let names = NameSetWithId {
        data: vec![
            RecordWithId {
                id: 34,
                _descr: "John".to_string(),
            },
            RecordWithId {
                id: 49,
                _descr: "Jane".to_string(),
            },
        ],
    };
    print!(
        "{}, {}; {} {}",
        names.count(48),
        names.count(49),
        is_present(&names, 48),
        is_present(&names, 49)
    );
}
/* It prints:
0, 1; false true*/
fn main() {
    trait Searchable { //1
        type Key; //2
        type Count; //3
        fn contains(&self, key: Self::Key) -> bool; //4
        fn count(&self, key: Self::Key) -> Self::Count; //5
    }
    struct RecordWithId {
        id: u32,
        _descr: String,
    }
    struct NameSetWithId {
        data: Vec<RecordWithId>,
    }
    impl Searchable for NameSetWithId { //6
        type Key = u32; //7
        type Count = usize; //8
        fn contains(&self, key: Self::Key) -> bool { //9
            for record in self.data.iter() {
                if record.id == key {
                    return true;
                }
            }
            false
        }
        fn count(&self, key: Self::Key) -> usize { //10
            let mut c = 0;
            for record in self.data.iter() {
                if record.id == key {
                    c += 1;
                }
            }
            c
        }
    }
    fn is_present<Collection>(
        coll: &Collection,
        id: <Collection as Searchable>::Key,//11
    ) -> bool
    where
        Collection: Searchable, //12
    {
        coll.contains(id)
    }
    let names = NameSetWithId {
        data: vec![
            RecordWithId {
                id: 34,
                _descr: "John".to_string(),
            },
            RecordWithId {
                id: 49,
                _descr: "Jane".to_string(),
            },
        ],
    };
    print!(
        "{}, {}; {} {}",
        names.count(48),
        names.count(49),
        is_present(&names, 48),
        is_present(&names, 49)
    );
}
// It does nothing.
fn main() {
    trait Iterator {
        type Item;
        fn next(&mut self) -> Option<Self::Item>;
    }
}
/* It prints:
Some(10), Some(11), Some(12), None, None, */
fn main() {
    trait MyIterator {
        type Item;
        fn next(&mut self) -> Option<Self::Item>;
    }
    struct MyRangeIterator<T> {
        current: T,
        limit: T,
    }
    impl MyIterator for MyRangeIterator<u32> {
        type Item = u32;
        fn next(&mut self) -> Option<Self::Item> {
            if self.current == self.limit {
                None
            } else {
                self.current += 1;
                Some(self.current - 1)
            }
        }
    }
    let mut range_it = MyRangeIterator {
        current: 10,
        limit: 13,
    };
    print!("{:?}, ", range_it.next());
    print!("{:?}, ", range_it.next());
    print!("{:?}, ", range_it.next());
    print!("{:?}, ", range_it.next());
    print!("{:?}, ", range_it.next());
}
/* It prints:
[10, 11, 12]; 20 21 22 23 */
fn main() {
    struct MyRangeIterator<T> {
        current: T,
        limit: T,
    }
    impl Iterator for MyRangeIterator<u32> {
        type Item = u32;
        fn next(&mut self) -> Option<Self::Item> {
            if self.current == self.limit {
                None
            } else {
                self.current += 1;
                Some(self.current - 1)
            }
        }
    }
    print!(
        "{:?}; ",
        MyRangeIterator {
            current: 10,
            limit: 13,
        }.collect::<Vec<_>>()
    );
    for i in (MyRangeIterator {
        current: 20,
        limit: 24,
    }) {
        print!("{} ", i);
    }
}
/* It prints:
None Some(22) None Some(43)*/
fn main() {
    fn get_third<Iter>(mut iterator: Iter) -> Option<Iter::Item>
    where
        Iter: std::iter::Iterator,
    {
        iterator.next();
        iterator.next();
        iterator.next()
    }
    print!(
        "{:?} {:?} {:?} {:?}",
        get_third(10..12),
        get_third(20..29),
        get_third([31, 32].iter()),
        get_third([41, 42, 43, 44].iter())
    );
}
/* It prints:
None Some(23) None Some(44)*/
fn main() {
    print!(
        "{:?} {:?} {:?} {:?}",
        (10..12).nth(2),
        (20..29).nth(2),
        ([31, 32].iter()).nth(2),
        ([41, 42, 43, 44].iter()).nth(2)
    );
}